Подтвердить что ты не робот

С++ эквивалент java.toString?

Я хотел бы контролировать то, что записано в потоке, т.е. cout, для объекта пользовательского класса. Возможно ли это на С++? В Java вы можете переопределить метод toString() для аналогичной цели.

4b9b3361

Ответ 1

В С++ вы можете перегрузить 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 << ")";
}

Ответ 2

Вы также можете сделать это таким образом, чтобы полиморфизм:

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

Ответ 4

В качестве расширения к тому, что сказал Джон, если вы хотите извлечь строковое представление и сохранить его в 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>.

Ответ 5

Ответ был дан. Но я хотел добавить конкретный пример.

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

В этом примере требуется понимание перегрузки оператора.