加号运算符重载
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;
};
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;//相当于p1.operaor+(p1)
cout<<"p3.m_A= "<<p3.m_A<<endl;
cout<<"p3.m_B= "<<p3.m_B<<endl;
}
int main()
{
test01();
return 0;
}
代码temp.m_A=this->m_A+p.m_A;为什么要用this->m_A,而不能用this.m_A呢
在 C++ 中,成员变量和成员函数之间的访问有一些细微的差别:
-
成员变量是对象的数据成员,通过对象访问时,使用
.
操作符。例如,如果this
是指向当前对象的指针,访问m_A
就应该使用this->m_A
或者简单写作m_A
。 -
成员函数是操作对象的函数,成员函数在使用时可以像普通函数那样调用,但它们隐含地将调用对象作为一个参数传递,这个参数就是
this
指针。因此,成员函数内部访问成员变量时,可以直接使用成员变量的名称来访问,因为编译器会自动解析到当前对象的成员变量。所以,在成员函数内部,可以直接写m_A
。
所以,对于代码中的 operator+
函数:
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;
}
this->m_A
是显式使用当前对象指针this
来访问成员变量m_A
。p.m_A
是访问参数p
对象的成员变量m_A
。
如果尝试使用 this.m_A
来访问成员变量,会导致编译错误,因为 this
是指针,而不是对象本身,不能使用.
操作符来访问其成员变量。
2、全局函数重载+号
#include<iostream>
using namespace std;
class Person
{
public:
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;//相当于operaor+(p1,p2)
cout<<"p3.m_A= "<<p3.m_A<<endl;
cout<<"p3.m_B= "<<p3.m_B<<endl;
}
int main()
{
test01();
return 0;
}
3、运算符重载,也可以发生函数重载
#include<iostream>
using namespace std;
class Person
{
public:
int m_A;
int m_B;
};
//2、全局函数重载+号
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=10;
p1.m_B=10;
Person p3=p1+20;
cout<<"p3.m_A= "<<p3.m_A<<endl;
cout<<"p3.m_B= "<<p3.m_B<<endl;
}
int main()
{
test01();
return 0;
}
- 不要滥用运算符重载