c++ ostream (tostring)的最佳实践

Best Practices with C++ ostream (tostring)

本文关键字:最佳 ostream tostring c++      更新时间:2023-10-16

重载<<操作符的最佳实践是什么?特别是,如何区分在指针上操作和在对象上操作。当输入到<<时,它们都输出相同的字符串是否合适?

例如,考虑以下代码,其中两个Book对象都已初始化
Book b1;
Book* b2;
// initialization stuff
// can both of these output the same representation of a book object?
cout << b1 << endl;
cout << b2 << endl;

如何区分指针操作和对象操作。

通过operator<<函数签名:

std::ostream& operator<<(std::ostream&, const Book&); // operates on object
std::ostream& operator<<(std::ostream&, const Book*); // operates on pointer

它们都输出相同的字符串是合适的吗?

这是允许的,但不是特别有用。很少看到第二种形式的实现。如果您想实现第二种形式,请认识到它完全是多余的。例如,如果您有一个Book* pBook:

std::cout << *pBook << "n";

这将打印出pBook所指向的对象。

不要重载指向T的指针的operator<<。相反,应该重载T本身(或者适当时重载const T&),并在调用operator<<时解引用指针。

cout << *b2 << endl;

为指向T的指针重载只会造成混淆和潜在的名称冲突,如果为const T&重载就没有必要了