运算符重载

重载+号运算符

在有些时候,比如重载加号运算符,能做一些普通的运算,却无法把两个类相加。可以重新定义+ 运算符

  • 重载+运算符的功能函数就是operator关键字,后边加要重载的符号。
  • 重载运算符可以重载函数,可以写多个版本的重载运算符,(类+类、类+整形、……)
  • 重载运算符函数可以写在类内也可以写在类外,一般写在类内能少些一个形参。
class Persion
{
public:
	int age;
	//成员函数重载
	Persion operator+(Persion & p);
};
Persion Persion::operator+(Persion & p)
{
	Persion itemp;
	itemp.age = this->age + p.age;
	return itemp;
}
//或者重载函数合一写到全局函数
Persion operator+(Persion &p1, Persion &p2)
{
	Persion itemp;
	itemp.age = p1.age + p2.age;
	return itemp;
}
Persion operator+(Persion &p1, int num)
{
	Persion itemp;
	itemp.age = p1.age + num;
	return itemp;
}

左移运算符重载

左移运算符用在 cout << ……这种形式,只能用来输出内置数据类型,如果我们想输出自定义数据类型,就需要重载左移运算符。
(1)从上边我们知道,重载运算符可以在类内,也可以在类外。如果在类内

class Persion
{
	void operator<<(cout)
	//这种写法在调用的时候,简化完之后就是 this << cout ,很显然不符合我们的要求(要求就是cout  必须在左边,而成员函数的写法,cout只能写在右边)
}

cout这种运算符一定能满足链式编程,所以返回值应该是指针或者引用

class Persion
{
public:
	int age;
	Persion(int age)
	{
		this->age = age;
	}
};
ostream& operator<<(ostream& cout, Persion& p)
{
	cout << p.age;
	return cout;
}
void text01(void)
{
	Persion p1(20);
	cout << p1 << endl;;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值