I'm using a C++ class provided by a 3rd party and therefore cannot modify it. It has numerous properti开发者_如何学Ces but no methods or operator overloading (<<
) to create formatted output. I could write a function that simply returns a string, but is there way better C++ way to create formatted output without modifying the class?
Yes. You can overload the stream insertion operator as a non-member function. The downside is of course that you can't make the function a friend (which is often done), so you won't be able to output anything that's not exposed by the class through a public accessor -- but you're limited in that regard no matter what you do if you can't modify the class.
Example:
class Foo {
public:
std::string name() const;
int number() const;
private:
// Don't care about what's 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;
精彩评论