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



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

326   5  
c++

5 ответов:

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

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

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

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

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

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

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

Comments

    Ничего не найдено.