关于C++全局重载运算符的两点注意

  1. 全局运算符重载要注意函数的声明
  2. 全局运算符重载中的等号是浅拷贝,并非深拷贝。

代码如下:

#include <iostream>
using namespace std;

class Person;
Person operator+(const Person &p1, const Person &p2); // 注意函数的声明

class Person{
public:
	int m_A;
	int m_B;
};

void test01(){

	Person p1;
	p1.m_A = 5;
	p1.m_B = 3;
	Person p2;
	p2.m_A = 2;
	p2.m_B = 7;

	// 关于什么时候调用拷贝构造函数,什么调用等号的载载,可以参考其他资料
	// 简单举例如下:
	// Person t = p1;	// 调用拷贝构造函数,因为t还没有被被始化
	// ----------
	// Person t;
	// t = p1;			// 调用等号的重载,因为t已经被构造,初始化
	
	Person p3 = p1 + p2;	// 此处使用的默认拷贝构造函数为浅拷贝

	cout << "p3.m_A = " << p3.m_A << endl;
	cout << "p3.m_B = " << p3.m_B << endl;
}
//2、全局函数重载+号
Person operator+(const Person &p1, const Person &p2){
	Person temp;
	temp.m_A = p1.m_A + p2.m_A;
	temp.m_B = p1.m_B + p2.m_B;
	return temp;
}
int main(){

	test01();
	return 0;
}
原文地址:https://www.cnblogs.com/laohaozi/p/12537565.html