C++ 中的 toString 重写
在 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
选择的一些有意义的字符串表示形式?
In Java, when a class overrides .toString()
and you do System.out.println()
it will use that.
class MyObj {
public String toString() { return "Hi"; }
}
...
x = new MyObj();
System.out.println(x); // prints Hi
How can I accomplish that in C++, so that:
Object x = new Object();
std::cout << *x << endl;
Will output some meaningful string representation I chose for Object
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果将其写入头文件中,请记住将该函数标记为内联:
inline std::ostream &运算符<<(...
(请参阅 C++ 超级常见问题解答 为什么。)If you write this in a header file, remember to mark the function inline:
inline std::ostream & operator<<(...
(See the C++ Super-FAQ for why.)作为埃里克解决方案的替代方案,您可以覆盖字符串转换运算符。
通过这种方法,您可以在需要字符串输出的任何地方使用对象。您不限于流。
然而,这种类型的转换运算符可能会导致无意的转换和难以追踪的错误。我建议仅将其与具有文本语义的类一起使用,例如
Path
、UserName
和SerialCode
。Alternative to Erik's solution you can override the string conversion operator.
With this approach, you can use your objects wherever a string output is needed. You are not restricted to streams.
However this type of conversion operators may lead to unintentional conversions and hard-to-trace bugs. I recommend using this with only classes that have text semantics, such as a
Path
, aUserName
and aSerialCode
.虽然运算符重写是一个很好的解决方案,但我对像下面这样的更简单的解决方案感到满意(这似乎也更适合 Java):
Though operator overriding is a nice solution, I'm comfortable with something simpler like the following, (which also seems more likely to Java) :