C++的cout
(控制臺(tái)輸出)是iostream庫(kù)的一部分,用于向標(biāo)準(zhǔn)輸出設(shè)備(通常是顯示器)打印數(shù)據(jù)。cout
可以處理各種基本數(shù)據(jù)類型和自定義數(shù)據(jù)類型。以下是一些常見(jiàn)的數(shù)據(jù)類型:
int
、short
、long
、long long
float
、double
、long double
char
、signed char
、unsigned char
std::string
void*
、char*
、int*
等bool
、wchar_t
等<<
運(yùn)算符使其支持cout
輸出。例如,以下代碼演示了如何使用cout
輸出各種數(shù)據(jù)類型:
#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;
}
如果需要輸出自定義類型,可以重載<<
運(yùn)算符:
#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;
}