- 定义好后用来计算比较方便
比如说 对象box1和对象box2内部某些固定的参数要进行的加法运算,一个个点出来加显然很麻烦,还是写个函数更简洁。
Box operator+(const Box&);
把函数写成这个样子,显然,很奇怪的函数。
拆开看const Box&就是这个函数的参数,operator+不用变,固定好的,这里面的Box可以换成自己定义的类名。
#includeusing namespace std; class Box { public: // 重载 + 运算符,用于把两个 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; } void output(void) { cout << "length :"< Box Box1; // 声明 Box1,类型为box Box Box2; // 声明 Box2,类型为box Box Box3; // 声明 Box3,类型为box // Box1 详述 Box1.length = 6.0; Box1.breadth = 7.0; Box1.height = 5.0; // Box2 详述 Box2.length = 12.0; Box2.breadth = 13.0; Box2.height = 10.0; // 把两个对象相加,得到 Box3 Box3 = Box1 + Box2; Box3.output(); return 0; }
来瞧瞧运算结果:
length :18 breadth :20 height :15
可以看出, 对象Box1和对象Box2的参数已经相加。
参考资料:C++ 重载运算符和重载函数



