我正在使用第三方提供的C ++类,因此无法对其进行修改。它有许多属性,但没有方法或运算符重载(<<
)来创建格式化输出。我可以编写一个只返回一个字符串的函数,但有没有更好的C ++方法来创建格式化输出而不修改类?
答案 0 :(得分:6)
是。您可以将流插入运算符作为非成员函数重载。缺点当然是你不能把这个功能变成朋友(这通常是完成的),所以你将无法通过公共访问者输出任何没有被类暴露的东西 - 但是你有限制无论你做什么,如果你不能修改课程。
示例:
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;