目录
运算符重载
运算符重载概念:对已有的运算符重新定义,赋予其另一种功能,以适应不同的数据类型
加法运算符重载
作用:实现两个自定义数据类型相加的运算
方法:
成员函数重载+号
示例:
//成员函数重载
Preson operator+(Preson &p)
{
Preson temp;
temp.m_A = this->m_A + p.m_A;
temp.m_B = this->m_B + p.m_B;
return temp;
}
全局函数重载+号
示例:
//全局函数重载
Preson operator+(Preson& P1, Preson& P2)
{
Preson temp;
temp.m_A = P1.m_A + P2.m_A;
temp.m_B = P1.m_B + P2.m_B;
return temp;
}
注:
Preson P3 = P1 + P2;//经过编译器简化
Preson P4 = operator+(P1, P2);//运算符重载的本质
再注:
1)对于内置的数据类型的表达式的运算符式不可改变的(就是自带的,已经设定好的,比如1+1 = 2,1-1 = 0;这些不能该,人家本来就有,改它干嘛,没有意义)
2)不要滥用运算符重载(就是operator后面写了个+号,但是你内部函数实现的确实-号,这样虽然没错,但是别人看你代码容易影响心态)
示例:
#include <iostream>
using namespace std;
class Preson {
public:
Preson()
{
m_A = 10;
m_B = 10;
}
//成员函数重载
/*Preson operator+(Preson &p)
{
Preson temp;
temp.m_A = this->m_A + p.m_A;
temp.m_B = this->m_B + p.m_B;
return temp;
}*/
public:
int m_A;
int m_B;
};
//全局函数重载
Preson operator+(Preson& P1, Preson& P2)
{
Preson temp;
temp.m_A = P1.m_A + P2.m_A;
temp.m_B = P1.m_B + P2.m_B;
return temp;
}
void test01()
{
Preson P1;
Preson P2;
Preson P3 = P1 + P2;//经过编译器简化
Preson P4 = operator+(P1, P2);//运算符重载的本质
cout << "P3中m_A的值 = " << P3.m_A << endl;
cout << "P3中m_B的值 = " << P3.m_B << endl;
cout << "P4中m_A的值 = " << P4.m_A << endl;
cout << "P4中m_B的值 = " << P4.m_B << endl;
}
int main()
{
test01();
system("pause");
return 0;
}