重载运算符

重载运算符的格式 返回值类型 operator 重载的预算符号(参数),其中this是一个对象参数,而且重载运算符必须符合原来的符号运输规则。

比较普通的重载,比如+,对象相加,我们就要在类中写一个重载+的函数,使得这个+成立:

class A
{
public :
	int age;
	int operator +(A const mya)
	{
		return this->age + mya.age;
	}
};

比较特殊一点的,重载>>和<< 实现cin>>对象;cout<<对象;这里要使用友元函数,因为如果在类中写的话,调用时不符合原来的运算规则。

class A
{
public :
	int age;
	int operator +(A const mya)
	{
		return this->age + mya.age;
	}

	friend istream& operator >> (istream& cin, A& mya);
	friend ostream& operator << (ostream& cout, A& mya);
};
istream& operator >> (istream& cin, A& mya)
{
	cin >> mya.age;
	return cin;
}
ostream& operator << (ostream& cout, A& mya)
{
	cout << mya.age << endl;
	return cout;
}

还有一个比较容易错的,就是重载*符号:

class A
{
public :
	A* mya;

	A& operator *()
	{
		return *this->mya;
	}
	 
};

tips:返回引用的话,我们就必须返回对象而不是对象的指针,所以必须是*this,而this是指针。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值