运算符重载

运算符重载概念:对已有的运算符重新进行定义,赋予其另外一种功能,以适应不同的数据类型。
对于内置的数据类型,编译器知道如何进行计算
int a=10;
int b=10;
int c=a+b;

#include
using namespace std;
//加号运算重载 
class Person
{
	public:
		
		//1、成员函数重载+号
		Person operator+(Person &p)
		{
			Person temp;
			temp.m_a=this->m_a+p.m_a;
			temp.m_b=this->m_b+p.m_b;
			return temp;
		 } 
		int m_a;
		int m_b;
};
void test01()
{
	Person p1;
	p1.m_a=10;
	p1.m_b=10; 
	Person p2;
	p2.m_a=10;
	p2.m_b=10;
	Person p3=p1+p2;
	cout<<"p3.m_a:"<<p3.m_a<<endl;
	cout<<"p3.m_b:"<<p3.m_b<<endl;
}
int main()
{
	test01();
	return 0;
}
#include
using namespace std;
//加号运算重载 
class Person
{
	public:
		
		//1、成员函数重载+号
	/*	Person operator+(Person &p)
		{
			Person temp;
			temp.m_a=this->m_a+p.m_a;
			temp.m_b=this->m_b+p.m_b;
			return temp;
		 } */
		
		int m_a;
		int m_b;
};
 //2、全局函数重载+号
	Person operator+(Person &p1,Person &p2)
	{
		Person temp;
		temp.m_a=p1.m_a+p2.m_a;
		temp.m_b=p1.m_b+p2.m_b;
		return temp;
	 } 
void test01()
{
	Person p1;
	p1.m_a=10;
	p1.m_b=10; 
	Person p2;
	p2.m_a=10;
	p2.m_b=10;
	Person p3=p1+p2;
	cout<<"p3.m_a:"<<p3.m_a<<endl;
	cout<<"p3.m_b:"<<p3.m_b<<endl;
}
int main()
{
	test01();
	return 0;
}
p3.m_a:20
p3.m_b:20

成员函数重载本质调用

Person p3=p1.operator+(p2);

全局函数重载本质调用

Person p3=operator+(p1,p2);

都可以简化为

Person p3=p1+p2;

运算符重载,也可以发生函数重载

你可能感兴趣的:(笔记)