C ++相当于Java的toString?

时间:2009-10-11 05:28:40

标签: c++

我想控制写入流的内容,即cout,以获取自定义类的对象。这可能在C ++中?在Java中,您可以为了类似的目的覆盖toString()方法。

5 个答案:

答案 0 :(得分:155)

在C ++中,您可以为operator<<和您的自定义类重载ostream

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

答案 1 :(得分:46)

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

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

答案 2 :(得分:27)

在C ++ 11中,to_string最终被添加到标准中。

http://en.cppreference.com/w/cpp/string/basic_string/to_string

答案 3 :(得分: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

std::stringstream位于<sstream>标题中。

答案 4 :(得分:6)

问题已得到解答。但我想补充一个具体的例子。

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

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