重载打印类的值

Overload print value of class

本文关键字:打印 重载      更新时间:2023-10-16

我可以重载返回值,例如对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以外的输出流类型,例如,文件。