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
?
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.)
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
.
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;
};
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;
}
精彩评论