我在使用Java很长一段时间后回到了c ++.在Java中,覆盖对象上的toString方法允许将对象自动转换为字符串并连接到其他字符串.
class Test {
public static void main(String[] args) {
System.out.println(new Test() + " There"); // prints hello there
}
public String toString() {
return "Hello";
}
}
Run Code Online (Sandbox Code Playgroud)
是否有类似的东西可以让我将一个对象流入cout?
cout << Test() << endl;
Run Code Online (Sandbox Code Playgroud)
相当于过载operator<<:
#include <ostream>
class Test
{
int t;
};
std::ostream& operator<<(std::ostream& os, const Test& t)
{
os << "Hello";
return os;
}
Run Code Online (Sandbox Code Playgroud)
然后你会像这样使用它:
#include <iostream>
int main()
{
std::cout << Test() << " There" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
请参阅操作代码:http://codepad.org/pH1CVYPR