C++ 运算符重载全面解析
1. 运算符重载基础示例
首先来看一个简单的示例,通过比较 Box 对象的体积来找出体积最小的 Box 对象:
int main()
{
std::vector<Box> boxes {Box {2.0, 2.0, 3.0}, Box {1.0, 3.0, 2.0},
Box {1.0, 2.0, 1.0}, Box {2.0, 3.0, 3.0}};
Box smallBox {boxes[0]};
for (auto& box : boxes)
{
if (box < smallBox) smallBox = box;
}
std::cout << "The smallest box has dimensions :"
<< smallBox.getLength() << "x" << smallBox.getWidth() << "x"
<< smallBox.getHeight() << std::endl;
}
上述代码的执行流程如下:
1. 创建一个包含四个 Box 对象的向量 boxes 。
2. 假设第一个 Box 对象是最小的,并用它初始化 smallBox
超级会员免费看
订阅专栏 解锁全文
5940

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



