复习运算符重载的时候发现一个小问题:在分别调用成员函数和全局函数时,出现了不一样的结果。在类内实现运算符重载,调用成员函数时,连加没有问题,而使用全局函数连加时则会报错。如图:
1.调用成员函数
#include<iostream>
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 = 20;
Person p2;
p2.m_A = 10;
p2.m_B = 20;
Person p6;
p6.m_A = 10;
p6.m_B = 20;
Person p3 = p1 + p2 + p6;
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();
}
而在调用全局函数时,则会报错 。之前在写代码时,用引用作为了返回值,后经评论区的一位朋友提醒,才想起局部变量返回引用引发的问题。去掉引用之后,代码如上。但是引发了一个新问题:
具体原因:目前还没搞明白。
后来发现,对加号运算符重载函数中的形参加上const之后,问题就得到了解决。很惭愧具体原因:现在没也不清楚。希望看到这篇文章的朋友,不吝赐教 。
写文章记录自己的学习历程和犯过的问题,希望未来可以解决。