c++ ostream (tostring)的最佳实践
Best Practices with C++ ostream (tostring)
重载<<
操作符的最佳实践是什么?特别是,如何区分在指针上操作和在对象上操作。当输入到<<
时,它们都输出相同的字符串是否合适?
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&
重载就没有必要了
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- ostream过载时的缓冲区冲洗
- 在c代码之间共享数据的最佳方式
- 使用std::source_location报告错误的最佳实践
- 派生类销毁的最佳实践是什么
- 需要从 istream 和 ostream 派生 iostream
- 将寄存器设计成可由C和C++访问的外设的最佳实践
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 在C++中向零方向近似的最佳方法
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- "ostream &os"有什么用?
- 检测win32服务创建和删除的最佳方法
- 在reactor中存储eventHandlers的最佳方式是什么
- c++ ostream (tostring)的最佳实践
- 专门化运算符的最佳方法<<用于 std::ostream 和 std::vector 与通用模板函数?