重载打印类的值
Overload print value of class
我可以重载返回值,例如对cout
函数?我有这样一个类:
class Xxx
{
string val = "3";
}
现在我想在cout
上返回"3"
,没有其他方法。我想要那个:
Xxx myVar;
cout<<myVar;
打印"3"
作为结果。
通常的方法是重载ostream& operator<<(ostream&, T)
。这里,为了简单起见,val
是公开的:
class Xxx
{
public:
std::string val = "3";
}
#include <ostream>
std::ostream& operator<<(std::ostream& o, const Xxx& x)
{
return o << x.val;
}
然后Xxx x;
std::cout << x << std::endl; // prints "3"
这种方法意味着您还可以将Xxx
的实例流式传输到std::cout
以外的输出流类型,例如,文件。
相关文章:
- 可以打印矢量和矢量中的矢量的非重载C++函数
- 链接列表运算符重载没有打印出我想要的内容
- cout (<<) 重载运算符不打印减去的矩阵
- 了解运算符重载和迭代器,为什么它会打印出"wrhrwwr"?
- 重载 std::字符串运算符+ 用于打印枚举名称
- oStream 不打印添加两个 valarray 的结果(使用运算符重载)
- C++ |<<运算符重载和打印字符串
- 我重载了 << 和 = 运算符。为什么当我将一个对象分配给另一个对象并尝试打印它时,我会被打印出来?
- 为什么重载运算符<<打印特征类成员会导致段错误?
- 重载运算符后打印二维数组<<
- 如何让我的重载<<运算符打印出我的函数?
- C++打印模板容器错误(错误:"运算符<<"的不明确重载)理解?
- Std::copy 和 std::ostream_iterator 使用重载函数打印值
- 如何使用 is_invocable() 创建用于重载<<打印对象的模板?
- 运算符重载<<,打印对象矢量时遇到问题
- 重载<<运算符打印向量的前n个值(不是整个向量)
- C++运算符<<重载不打印出向量
- 重载函数打印
- 有没有办法在不重载<<运算符的情况下打印出 std::list 的内容?
- 打印任何带有非成员ostream重载函数的c++11数组