相当于java.toString的C ++?
我想控制什么写入stream,即cout ,为自定义类的对象。 在C ++中可能吗? 在Java中,你可以重写toString()方法来达到类似的目的。 
 在C ++中,您可以重载operator<< for ostream和您的自定义类: 
 class A { public: int i; }; std::ostream& operator<<(std::ostream &strm, const A &a) { return strm << "A(" << ai << ")"; } 
这样你就可以在stream上输出你的类的实例了:
 A x = ...; std::cout << x << std::endl; 
 如果您的operator<<想要打印A类内部实际需要访问其私有和受保护的成员,则还可以将其声明为朋友函数: 
 class A { private: friend std::ostream& operator<<(std::ostream&, const A&); int j; }; std::ostream& operator<<(std::ostream &strm, const A &a) { return strm << "A(" << aj << ")"; } 
你也可以这样做,允许多态:
 class Base { public: virtual std::ostream& dump(std::ostream& o) const { return o << "Base: " << b << "; "; } private: int b; }; class Derived : public Base { public: virtual std::ostream& dump(std::ostream& o) const { return o << "Derived: " << d << "; "; } private: int d; } std::ostream& operator<<(std::ostream& o, const Base& b) { return b.dump(o); } 
在C ++ 11中,to_string最终被添加到标准中。
http://en.cppreference.com/w/cpp/string/basic_string/to_string
 作为约翰所说的扩展,如果你想提取string表示并将其存储在std::string请执行以下操作: 
 #include <sstream> // ... // Suppose a class A A a; std::stringstream sstream; sstream << a; std::string s = sstream.str(); // or you could use sstream >> s but that would skip out whitespace 
  std::stringstream位于<sstream>标头中。 
这个问题已经回答了。 但是我想添加一个具体的例子。
 class Point{ public: Point(int theX, int theY) :x(theX), y(theY) {} // Print the object friend ostream& operator <<(ostream& outputStream, const Point& p); private: int x; int y; }; ostream& operator <<(ostream& outputStream, const Point& p){ int posX = px; int posY = py; outputStream << "x="<<posX<<","<<"y="<<posY; return outputStream; } 
这个例子需要理解操作符超载。