C++的cout
(控制臺輸出)是iostream庫的一部分,用于向標準輸出設備(通常是顯示器)打印數據。cout
可以處理各種基本數據類型和自定義數據類型。以下是一些常見的數據類型:
int
、short
、long
、long long
float
、double
、long double
char
、signed char
、unsigned char
std::string
void*
、char*
、int*
等bool
、wchar_t
等<<
運算符使其支持cout
輸出。例如,以下代碼演示了如何使用cout
輸出各種數據類型:
#include <iostream>
#include <string>
int main() {
int a = 42;
double b = 3.14;
char c = 'A';
std::string s = "Hello, World!";
bool d = true;
std::cout << "a: "<< a << std::endl;
std::cout << "b: "<< b << std::endl;
std::cout << "c: "<< c << std::endl;
std::cout << "s: "<< s << std::endl;
std::cout << "d: "<< d << std::endl;
return 0;
}
如果需要輸出自定義類型,可以重載<<
運算符:
#include <iostream>
class MyClass {
public:
MyClass(int x, int y) : x_(x), y_(y) {}
friend std::ostream& operator<<(std::ostream& os, const MyClass& obj);
private:
int x_;
int y_;
};
std::ostream& operator<<(std::ostream& os, const MyClass& obj) {
os << "(" << obj.x_ << ", " << obj.y_ << ")";
return os;
}
int main() {
MyClass obj(3, 4);
std::cout << "obj: " << obj << std::endl;
return 0;
}