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

类和对象–C++运算符重载

C++ 预定义的运算符,只能用于基本数据类型的运算,不能用于对象的运算
如何使运算符能用于对象之间的运算呢

加号运算符重载

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

1.对于两个基本数据类型间的运算

代码:
在这里插入图片描述
运行结果:
在这里插入图片描述

对于两个对象之间的加法运算,例如两个person之间的加法运算 我们需要用到 operator+

2.成员函数实现 + 号运算符重载(成员函数写在类内)

代码:
在这里插入图片描述

运行结果:

在这里插入图片描述

3.全局函数实现 + 号运算符重载(全局函数写在类外)
代码:
在这里插入图片描述

运行结果:
在这里插入图片描述
4.对象与基本数据类型相加

扫描二维码关注公众号,回复: 12464833 查看本文章

代码:

在这里插入图片描述
运行结果:

在这里插入图片描述

全部代码

#include <iostream>
using namespace std;
class Person {
    
    
public:
	Person operator+(const 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;
};

int main() {
    
    
			Person p1; 
			p1.m_A = 10;
			p1.m_B = 10; 
			Person p2;
			p2.m_A = 10; 
			p2.m_B = 10; 
			Person p3 = p2 + p1; 
			cout << "p3.m_A= " << p3.m_A << endl; 
			cout << "p3.m_B= " << p3.m_B << endl;
		
}
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;

};

int main() {
    
    	
			int a = 15;
			int b = 15; 
			int c = a + b; 
			cout << "c= " << c << endl; 
			Person p1; 
			p1.m_A = 10; 
			p1.m_B = 10; 
			Person p2;
			p2.m_A = 10; 
			p2.m_B = 10;
			Person p3 = p2 + p1; 
			Person p4 = p1 + 100; 
			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; 
}

猜你喜欢

转载自blog.csdn.net/weixin_48245161/article/details/112971299