【C++】运算符重载

加号运算符重载

成员函数实现

#include<iostream>
using namespace std;

class Person {
public:
	int a;
	int b;
	Person(){}
	Person(int a, int b)
	{
		this->a = a;
		this->b = b;
	}

	Person operator+(const Person& p)
	{
		Person temp;
		temp.a = this->a + p.a;
		temp.b = this->b + p.b;
		return temp;
	}

	//运算符重载 也可发生函数重载
	Person operator+(int val)
	{
		Person temp;
		temp.a = this->a + val;
		temp.b = this->b + val;
		return temp;
	}
};

int main()
{
	Person p1(10, 10);
	Person p2(10, 10);
	Person p3 = p1 + p2 + 20;//相当于(p1.operator+(p2)).operator(20)
	cout << "p3.a=" << p3.a << " p3.b=" << p3.b<<endl;
}

全局函数实现

#include<iostream>
using namespace std;

class Person {
public:
	int a;
	int b;
	Person(){}
	Person(int a, int b)
	{
		this->a = a;
		this->b = b;
	}

};

Person operator+(const Person& p1, const Person& p2)
{
	Person temp;
	temp.a = p1.a + p2.a;
	temp.b = p1.b + p2.b;
	return temp;
}

//运算符重载 可以发生函数重载 
Person operator+(const Person& p1,int val)
{
	Person temp;
	temp.a = p1.a + val;
	temp.b = p1.b + val;
	return temp;
}

int main()
{
	Person p1(10, 10);
	Person p2(10, 10);
	Person p3 = p1 + p2 + 20;//相当于(p1.operator+(p2)).operator(20)
	cout << "p3.a=" << p3.a << " p3.b=" << p3.b<<endl;
}

左移运算符重载

成员函数无法实现

class Person {
public:
	int a;
	int b;
	Person(int a, int b)
	{
		this->a = a;
		this->b = b;
	}

	//因为重载运算符为成员函数后,当调用该运算符时,左操作数必须是该类的实例。如果支持成员函数实现的话,输出流的语句写法就变成了obj<<cout,不是想要的效果;
	ostream& operator<<(Person& p)
	{
		cout << "p.a=" << p.a << " p.b=" << p.b << endl;
		//返回cout的引用out才能进行后续的<<的链式编程
		return cout;
	}
};

全局函数实现

#include<iostream>
using namespace std;

class Person {
public:
	int a;
	int b;
	Person(int a, int b)
	{
		this->a = a;
		this->b = b;
	}
};

//ostream 对象只能有一个,所以只能使用cout的引用
ostream& operator<<(ostream& out,Person& p)
{
	out << "p.a=" <<p.a<< " p.b=" <<p.b<< endl;
	//返回cout的引用out才能进行后续的<<的链式编程
	return out;
}

//取消<<号的链式编程
//void operator<<(ostream& out, Person& p)
//{
//	out << "p.a=" << p.a << " p.b=" << p.b << endl;
//}


int main()
{
	Person p(10, 20);
	//cout << p;//取消链式编程后只支持一个<<号,使用链式编程会报错
	cout << p<<"hello world!";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值