C++ 中的 toString 覆盖

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5171739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:35:59  来源:igfitidea点击:

toString override in C++

c++tostring

提问by Aillyn

In Java, when a class overrides .toString()and you do System.out.println()it will use that.

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

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:

我怎样才能在 C++ 中实现这一点,以便:

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

Will output some meaningful string representation I chose for Object?

会输出一些我选择的有意义的字符串表示Object吗?

回答by Erik

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

如果你把它写在头文件中,记得把函数标记为内联:(inline std::ostream & operator<<(...请参阅 C++ Super-FAQ了解为什么。)

回答by Tugrul Ates

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

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

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 UserNameand a SerialCode.

然而,这种类型的转换运算符可能会导致无意的转换和难以追踪的错误。我建议仅将它用于具有文本语义的类,例如 a Path、 aUserName和 a SerialCode

回答by Parsa Jamshidi

 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;
 };

回答by Touhid

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

尽管运算符覆盖是一个不错的解决方案,但我对以下更简单的东西感到满意(这似乎也更可能适用于 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;
}