类和对象-运算符重载-1、加减号运算符重载

类和对象-运算符重载

运算符重载念:对已有的运算符重新进行定义,賦予其另一种功能·以适应不同的数据类型

加减号运算符重载

作用:实现两个自定义数据类型相加减的运算

#include<iostream>
#include<string>
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;
}
person operator+(person& p1, int num)//函数重载
{
    
    
	person temp;
	temp.m_A = p1.m_A + num;
	temp.m_B = p1.m_B + num;
	return temp;
}
void test01()
{
    
    
	person p1;
	p1.m_A = 233;
	p1.m_B = 233;
	person p2;
	p2.m_A = 137;
	p2.m_B = 137;
	person p3;	
	p3 = p1.operator+(p2);//成员函数本质
	cout << "p3为" << p3.m_A << "--" << p3.m_B << endl;
	p3 = operator-(p1, p2);//全局函数本质
	p3 = p1 + p2;
	cout << "p3为" << p3.m_A << "--" << p3.m_B << endl;
	p3 = p1 - p2;
	cout << "p3为" << p3.m_A << "--" << p3.m_B << endl;
	//运算符重载也可以发生函数重载
	person p4 = p1 + 10;//person + int 
	cout << "p4为" << p4.m_A << "--" << p4.m_B << endl;

}
int main()
{
    
    
	test01();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_54673833/article/details/114125405
今日推荐