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