C++ 成员重载运算符

+ 运算符一般用于基本类型的增加,如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类型变量的引用。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值