【问题标题】:How to print the objects specific member using only object name? [duplicate]如何仅使用对象名称打印对象特定成员? [复制]
【发布时间】:2020-11-02 06:17:54
【问题描述】:
string var = "Hello";
cout << var << endl;
我们只使用对象获得结果,无需成员变量的帮助。我想实现一个像string 一样工作的类。例如:
class Test {
public:
int x = 3;
};
Test var2;
cout << var2 << endl;
我怎样才能实现类,以便cout 行打印x 的值而不引用它?
【问题讨论】:
标签:
c++
output
operator-overloading
【解决方案1】:
std::string 类的运算符 << 重载,这就是为什么当你写的时候:
std::string text = "hello!";
std::cout << var1 << std::endl; // calling std::string's overloaded operator <<
简单地打印它持有的文本。
因此,您需要为该类重载<< 运算符:
class Test {
int x = 3;
public:
friend std::ostream& operator<<(std::ostream& out, const Test& t) {
out << t.x;
return out;
}
}
// ...
Test var2;
std::cout << var2 << std::endl;