C++ 中的二元运算符重载
二元运算符接受两个参数,以下是二元运算符的示例。二元运算符非常常用,例如加法 (+)、减法 (-) 和除法 (/)。
以下示例解释了如何重载加法 (+)。类似地,减法 (-) 和除法 (/) 运算符也可以重载。
#include <iostream>
using namespace std;
class Box {
double length; // box 盒子的长度
double breadth; // box 盒子的宽度
double height; // box 盒子的高度
public:
double getVolume(void) {
return length * breadth * height;
}
void setLength( double len ) {
length = len;
}
void setBreadth( double bre ) {
breadth = bre;
}
void setHeight( double hei ) {
height = hei;
}
// 重载 + 运算符以添加两个 Box 对象。
Box operator+(const Box& b) {
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
};
// 程序的主函数
int main() {
Box Box1; // 声明 Box1 类型为 Box
Box Box2; // 声明 Box2 类型为 Box
Box Box3; // 声明 Box3 类型为 Box
doublevolume = 0.0; // 在此处存储盒子的体积
// Box1 的规格
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// Box2 的规格
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// Box1 的体积
volume = Box1.getVolume();
cout << "Box1 的体积:" << volume <<endl;
// box 2 的体积
volume = Box2.getVolume();
cout << "Box2 的体积:" << volume <<endl;
// 添加两个对象如下:
Box3 = Box1 + Box2;
// box 3 的体积
volume = Box3.getVolume();
cout << "Box3 的体积:" << volume <<endl;
return 0;
}
当编译并执行上述代码时,它会产生以下结果 -
Box1 的体积:210 Box2 的体积:1560 Box3 的体积:5400

cpp_overloading.html