我想控制写入流的内容,即cout自定义类的对象.这可能在C++中?在Java中,您可以toString()为了类似的目的覆盖该方法.
sth*_*sth 167
在C++中,你可以重载operator<<为ostream你的自定义类:
class A {
public:
int i;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.i << ")";
}
Run Code Online (Sandbox Code Playgroud)
这样您就可以在流上输出类的实例:
A x = ...;
std::cout << x << std::endl;
Run Code Online (Sandbox Code Playgroud)
如果您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(" << a.j << ")";
}
Run Code Online (Sandbox Code Playgroud)
fni*_*eto 50
你也可以这样做,允许多态:
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); }
Run Code Online (Sandbox Code Playgroud)
小智 28
在C++ 11中,to_string最终被添加到标准中.
http://en.cppreference.com/w/cpp/string/basic_string/to_string
blw*_*y10 10
作为John所说的扩展,如果你想提取字符串表示并将其存储在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
Run Code Online (Sandbox Code Playgroud)
std::stringstream位于<sstream>标题中.
小智 7
问题已得到解答.但我想补充一个具体的例子.
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 = p.x;
int posY = p.y;
outputStream << "x="<<posX<<","<<"y="<<posY;
return outputStream;
}
Run Code Online (Sandbox Code Playgroud)
此示例需要了解操作员过载.