在 Java 中,当一个类覆盖 .toString()
并且您执行 System.out.println()
时,它将使用它。
class MyObj {
public String toString() { return "Hi"; }
}
...
x = new MyObj();
System.out.println(x); // prints Hi
如何在 C++ 中实现这一点,以便:
Object x = new Object();
std::cout << *x << endl;
会输出一些我为 Object
选择的有意义的字符串表示形式吗?
最佳答案
std::ostream & operator<<(std::ostream & Str, Object const & v) {
// print something from v to str, e.g: Str << v.getX();
return Str;
}
如果你把它写在头文件中,记得把函数标记为内联:inline std::ostream & operator<<(...
(参见 C++ super 常见问题解答 for why。)
关于c++ - C++ 中的 toString 覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5171739/