相当于 Java 的 toString?

我想控制写入流中的内容,也就是自定义类的对象的 cout。在 C + + 中这可能吗?在 Java 中,可以为了类似的目的重写 toString()方法。

124749 次浏览

在 C + + 中,你可以为 ostream和你的定制类重载 operator<<:

class A {
public:
int i;
};


std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.i << ")";
}

通过这种方式,您可以在流上输出类的实例:

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(" << a.j << ")";
}

作为对 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

std::stringstream位于 <sstream>头部。

您也可以这样做,允许多态性:

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

这个问题已经得到了回答,但是我想补充一个具体的例子。

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

此示例需要理解运算符重载。