在C++中,一些运算符可以进行重载,重载后的运算符在原有功能的基础上增加一些新的功能。从本质上看,运算符重载就是函数重载,只是这个运算符换成了运算符
#include
using namespace std;
class Box
{
public:
double height;
double length;
Box operator+(const Box &b);
};
Box Box::operator+(const Box &b)
{
Box box;
box.height = this->height + b.height;
box.length = this->length + b.length;
return box;
}
int main()
{
Box b1;
Box b2;
Box b3;
b1.height = 1.1;
b1.length = 1.9;
b2.height = 2.1;
b2.length = 0.9;
b3 = b1 + b2;
cout << b3.height << endl
<< b3.length << endl
<< 1 + 2 << endl;
}
3.2
2.8
3