c++重载运算符笔记
1 、为什么要用这个功能?
- 定义好后用来计算比较方便
比如说 对象box1
和对象box2
内部某些固定的参数要进行的加法运算,一个个点出来加显然很麻烦,还是写个函数更简洁。
2、怎么写这个功能?
Box operator+(const Box&);
把函数写成这个样子,显然,很奇怪的函数。
拆开看const Box&
就是这个函数的参数,operator+
不用变,固定好的,这里面的Box
可以换成自己定义的类名。
3、写个例子
#include <iostream>
using 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 :"<<length << '\n'
<< endl;
cout << "breadth :"<<breadth << '\n'
<< endl;
cout << "height :"<<height << '\n'
<< endl;
}
double length; // 长度
double breadth; // 宽度
double height; // 高度
};
// 程序的主函数
int main()
{
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++ 重载运算符和重载函数