在C ++中的toString重写 [英] toString override in C++

查看:913
本文介绍了在C ++中的toString重写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,当一个类覆盖 .toString()并且你 System.out.println()它将使用那个。

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

如何在C ++中完成,
$ b

How can I accomplish that in C++, so that:

Object x = new Object();
std::cout << *x << endl;

将输出一些有意义的字符串表示,我选择 Object

Will output some meaningful string representation I chose for Object?

推荐答案

std::ostream & operator<<(std::ostream & Str, Object const & v) { 
  // print something from v to str, e.g: Str << v.getX();
  return Str;
}

如果将其写入头文件,请记住将函数标记为inline: inline std :: ostream& operator<<<(... (请参阅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.)

这篇关于在C ++中的toString重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆