Q1: line45为什么没有调用拷贝构造函数?
Q2: line28 中的return temp,是不是返回的temp地址值?
//运算符重载
//概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型
//加号运算符重载
//例,目标:实现两个对象的属性相加后返回新的对象
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
Person()//函数的无参构造,即当写Person p1;时,为p1调用的函数,此时p1的A=1,B=1;
{
m_A=1;
m_B=1;
}
Person(int a, int b):m_A(a),m_B(b)//初始化列表: 表函数的有参与构造,即写person p1(2,2);时,可为p1的成员赋值 见p111,
{
m_A=a;
m_B=b;
}
Person operator+ (Person &p)//有参构造函数
{
Person temp;//实例化一个 Person类
temp.m_A=this->m_A+p.m_A;
temp.m_B=this->m_B+p.m_B;
return temp;//返回其地址
}
Person(const Person& p)//拷贝构造函数
{
cout<<"调用Person的拷贝构造函数!"<<endl;
m_A=p.m_A;
m_B=p.m_B;
}
public:
int m_A;
int m_B;
};
void test01()
{
Person p1(10,10);
Person p2;
Person p3=p1+p2;//因为operator+返回值为 temp,(Person类),所以相当于person
cout<<"p3的m_A= "<<p3.m_A<<endl;
cout<<"p3的m_B= "<<p3.m_B<<endl;
}
void test02()
{
Person t1(5,5);
Person t2=t1;//此line调用了拷贝构造函数
//Person t3(t2);//此line调用了拷贝构造函数
}
int main()
{
test01();
//test02();
return 0;
}
Q1: line45为什么没有调用拷贝构造函数?----调用了啊
Q2: line28 中的return temp,是不是返回的temp地址值?---不是,返回一个类对象的拷贝
编译环境 2021Macbook Pro VScode