C++ 中的 toString 重写

发布于 2024-10-20 03:33:02 字数 408 浏览 6 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

中二柚 2024-10-27 03:33:02
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 &运算符<<(...(请参阅 C++ 超级常见问题解答 为什么。)

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

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.)

樱花坊 2024-10-27 03:33:02

作为埃里克解决方案的替代方案,您可以覆盖字符串转换运算符。

class MyObj {
public:
    operator std::string() const { return "Hi"; }
}

通过这种方法,您可以在需要字符串输出的任何地方使用对象。您不限于流。

然而,这种类型的转换运算符可能会导致无意的转换和难以追踪的错误。我建议仅将其与具有文本语义的类一起使用,例如 PathUserNameSerialCode

Alternative to Erik's solution you can override the string conversion operator.

class MyObj {
public:
    operator std::string() const { return "Hi"; }
}

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, a UserName and a SerialCode.

饮惑 2024-10-27 03:33:02
 class MyClass {
    friend std::ostream & operator<<(std::ostream & _stream, MyClass const & mc) {
        _stream << mc.m_sample_ivar << ' ' << mc.m_sample_fvar << std::endl;
    }

    int m_sample_ivar;
    float m_sample_fvar;
 };
 class MyClass {
    friend std::ostream & operator<<(std::ostream & _stream, MyClass const & mc) {
        _stream << mc.m_sample_ivar << ' ' << mc.m_sample_fvar << std::endl;
    }

    int m_sample_ivar;
    float m_sample_fvar;
 };
So尛奶瓶 2024-10-27 03:33:02

虽然运算符重写是一个很好的解决方案,但我对像下面这样的更简单的解决方案感到满意(这似乎也更适合 Java):

char* MyClass::toString() {
    char* s = new char[MAX_STR_LEN];
    sprintf_s(s, MAX_STR_LEN, 
             "Value of var1=%d \nValue of var2=%d\n",
              var1, var2);
    return s;
}

Though operator overriding is a nice solution, I'm comfortable with something simpler like the following, (which also seems more likely to Java) :

char* MyClass::toString() {
    char* s = new char[MAX_STR_LEN];
    sprintf_s(s, MAX_STR_LEN, 
             "Value of var1=%d \nValue of var2=%d\n",
              var1, var2);
    return s;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文