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;
}