我在使用了很长时间的 Java 之后又回到了 C++。在 Java 中,覆盖对象上的 toString 方法允许将对象自动转换为字符串并连接到其他字符串。
class Test {
public static void main(String[] args) {
System.out.println(new Test() + " There"); // prints hello there
}
public String toString() {
return "Hello";
}
}
是否有类似的东西可以让我将对象流式传输到 cout 中?
cout << Test() << endl;
最佳答案
相当于重载operator<<
:
#include <ostream>
class Test
{
int t;
};
std::ostream& operator<<(std::ostream& os, const Test& t)
{
os << "Hello";
return os;
}
然后你会像这样使用它:
#include <iostream>
int main()
{
std::cout << Test() << " There" << std::endl;
}
查看实际代码:http://codepad.org/pH1CVYPR
关于c++ - 将对象格式化为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7457959/