C++ 运算符重载的深入解析与实践
1. 输出运算符重载
在 C++ 中,我们可以对输出运算符 << 进行重载,使得自定义类的对象能够像基本类型变量一样输出到标准输出流。例如,对于 Box 类,我们可以通过重载 << 运算符,让 Box 对象的输出更加自然。
// 在 Box 类定义中添加友元声明
friend std::ostream& operator<<(std::ostream& stream, const Box& box);
// 实现友元函数
inline std::ostream& operator<<(std::ostream& stream, const Box& box)
{
stream << " Box(" << std::setw(2) << box.length << ","
<< std::setw(2) << box.width << ","
<< std::setw(2) << box.height << ")";
return stream;
}
通过上述代码,我们可以直接使用 std::cout << box; 来输出 B
超级会员免费看
订阅专栏 解锁全文
36

被折叠的 条评论
为什么被折叠?



