- 全局运算符重载要注意函数的声明
- 全局运算符重载中的等号是浅拷贝,并非深拷贝。
代码如下:
#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
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/326828
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!