+ 运算符一般用于基本类型的增加,如int,double类型等,也可用于字符串的连接;
以下代码演示C++ 对运算符+进行重载,使+ 运算符能用于两个Box类型的变量进行求和操作。
#include <iostream>
using namespace std;
class Box{
private:
int m_length;
int m_height;
int m_width;
public:
Box(); //默认构造函数
Box(int length,int width, int height); //构造函数
int show_volume(); //输出体积
Box operator+(const Box &b1) const; //重载Box 类的+运算符
};
Box::Box(int length,int width, int height){ //构造函数,创建对象时,对长、宽、高进行初始化
m_length = length;
m_height = height;
m_width = width;
}
Box::Box(){ //默认构造函数
m_length = 1;
m_height = 2;
m_width = 3;
}
Box Box::operator+(const Box &b1)const { //重载运算符定义,对Box类的长宽高进行分别进行+运算,并返回一个Box类型
Box box;
box.m_length = m_length + b1.m_length;
box.m_width = m_width + b1.m_width;
box.m_height = m_height + b1.m_height;
return box;
}
int Box::show_volume(){ //输出体积
cout<<m_length * m_width * m_height<<endl;
}
int main(){
Box box1(1,2,3);
Box box2(2,3,4);
Box box3;
Box box4;
box3 = box1 + box2; //等价box3 = box1.operator+(box2);
box4 = box1.operator+(box2);// 等价box4 = box1 + box2;
box3.show_volume();
box4.show_volume();
}
Box Box::operator+(const Box &b1)const;这种表示方法,和普通的类成员函数方法很类似,如:Box Box:funct1(const Box &b1)const;只不过成员函数名改成了operator+而已。
重载+运算符后,+运算符可用于Box类型的对象,如看起来较容易理解的调用方法:
box3 = box1.operator+(box2);
其实还有一种更简单的调用+运算符的方法:
box3 = box1 + box2;
这两种方式是等价的。第二种方式可以理解为由+号左边的对象box1调用operator+()函数,而+号box2则作为参数,即方式一。
重载函数中包含了很多Box,下面对每个Box的作用进行说明:
第一个”Box” 说明+运算符类型返回的是Box类型的值;
第二个”Box”说明该+操作符的只作用于Box类型;
第三个”Box”说明传递参数为Box类型变量的引用。