C ++ formatting class?

I am using a C ++ class provided by a third party and therefore cannot modify it. It has many properties, but does not have methods or operator overloads ( <<) to create formatted output. I could write a function that just returns a string, but is there a C ++ way to format the output without changing the class?

+3
source share
1 answer

Yes. You can overload the thread insert statement as a non-member function. The disadvantage, of course, is that you cannot make the function a friend (which is often done), so you won’t be able to output anything that was not opened by the class through a public accessor, but you are limited in that no matter what you do, if you cannot change the class.

Example:

class Foo {
  public:
    std::string name() const;
    int number() const;
  private:
    // Don't care about what in here; can't access it anyway.
};

// You write this part:

std::ostream& operator<< (std::ostream& os, const Foo& foo) {
  // Format however you like in here, e.g.
  os << "(" << foo.name() << "," << foo.number() << ")";
  return os;
}

// Then you can write:

Foo foo;
std::out << foo;
+6
source

All Articles