类和对象-C++运算符重载-加号运算符重载

加号运算符重载

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++ 中,成员变量和成员函数之间的访问有一些细微的差别:

  1. 成员变量是对象的数据成员,通过对象访问时,使用.操作符。例如,如果 this 是指向当前对象的指针,访问 m_A 就应该使用 this->m_A 或者简单写作 m_A

  2. 成员函数是操作对象的函数,成员函数在使用时可以像普通函数那样调用,但它们隐含地将调用对象作为一个参数传递,这个参数就是 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;
}
  • 不要滥用运算符重载
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值