C++, эквивалентный из toString Java?

Необходимо проверить Xstream. Существует 2-минутное учебное руководство, которое является действительно просто . Для получения того же формата Вы смоделировали бы классы то же.

144
задан Zoe 16 December 2018 в 19:18
поделиться

3 ответа

In C++ you can overload operator<< for ostream and your custom class:

class A {
public:
  int i;
};

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

This way you can output instances of your class on streams:

A x = ...;
std::cout << x << std::endl;

In case your operator<< wants to print out internals of class A and really needs access to its private and protected members you could also declare it as a friend function:

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 << ")";
}
167
ответ дан 23 November 2019 в 22:54
поделиться

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

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); }
50
ответ дан 23 November 2019 в 22:54
поделиться

As an extension to what John said, if you want to extract the string representation and store it in a std::string do this:

#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 is located in the header.

10
ответ дан 23 November 2019 в 22:54
поделиться
Другие вопросы по тегам:

Похожие вопросы: