C++ equivalent van Java’s Tostring?

Ik wil graag controleren wat er is geschreven aan een stroom, d.w.z. cout, voor een object van een aangepaste klasse. Is dat mogelijk in C++? In Java zou je de toString()-methode voor hetzelfde doel kunnen overschrijven.


Antwoord 1, Autoriteit 100%

In C++ kunt u overbelasten operator<<voor ostreamen uw aangepaste klasse:

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

Op deze manier kunt u exemplaren uitvoeren van uw klasse op streams:

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

In het geval dat uw operator<<wil afdrukken van internals van de klas Aen heeft echt toegang tot zijn privé- en beschermde leden nodig die u het ook als vriend kunt declareren Functie:

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

Antwoord 2, Autoriteit 28%

U kunt het ook op deze manier doen, waardoor polymorfisme is:

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

Antwoord 3, autoriteit 16%

In C++11 wordt to_string eindelijk toegevoegd aan de standaard.

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


Antwoord 4, autoriteit 6%

Als een uitbreiding op wat John zei, als je de tekenreeksrepresentatie wilt extraheren en opslaan in een std::string, doe dit dan:

#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::stringstreambevindt zich in de <sstream>-header.


Antwoord 5, autoriteit 5%

De vraag is beantwoord. Maar ik wilde een concreet voorbeeld toevoegen.

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

Dit voorbeeld vereist inzicht in overbelasting van de operator.

Other episodes