四、运算符重载(Operator OverLoad)

运算符重载的本质是函数重载

格式:

返值类型 operator 运算符名称(形参表列) {

重载实体;

}

operator 运算符名称 在一起构成了新的函数名。

4.1  友元重载

class A{
public:
	A(int _aa):aa(_aa){};
	inline void print(){
		cout << aa << endl;
	}

	friend const A operator+(const A &a1, const A &a2);

private:
	int aa;
};

//全局友元操作符重载
const A operator+(const A &a1, const A &a2){
	return A(a1.aa+a2.aa);
}

int main(){
	A a1(1);
	A a2(2);
	
	A a3 = operator+(a1, a2);//显示调用
	// A a3 = a1+ a2;//隐式调用
	a3.print();
	return 0;
}

4.2  成员重

#include <iostream>

using namespace std;

class Complex
{
public:
	Complex(float x=0, float y=0)
	:_x(x),_y(y){}

	void dis()
	{
	cout<<"("<<_x<<","<<_y<<")"<<endl;
	}
	friend const Complex operator+(const Complex &c1,const Complex &c2);
	const Complex operator+(const Complex &another);

private:
	float _x;
	float _y;
};

const Complex operator+(const Complex &c1,const Complex &c2)
{
	cout<<"友元函数重载"<<endl;
	return Complex(c1._x + c2._x,c1._y + c2._y);
}

const Complex Complex::operator+(const Complex & another)
{
	cout<<"成员函数重载"<<endl;
	return Complex(this->_x + another._x,this->_y + another._y);
}

int main()
{
	Complex c1(2,3);
	Complex c2(3,4);
	c1.dis();
	c2.dis();
	//
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值