我是 C++ 的初学者,我使用的资源表明以下语句 d3 = d1 + d2; 调用以下内容:
- + 运算符
- 默认构造函数
- 拷贝构造函数
- 析构函数
- 赋值运算符
- 析构函数
我不明白为什么在将结果分配给先前声明的变量时调用复制构造函数以及为什么调用 2 个构造函数。
运算符如下:
date& date::operator=(const date& other)
{
cout << "Date assignment op" << endl;
if (this!=&other){
day=other.day;
month=other.month;
year=other.year;
}
return *this;
}
date date::operator+(const date& other) const
{
cout << "Date Operator + called" << endl;
date temp;
temp.day=day+other.day;
temp.month=month+other.month;
temp.year=year+other.year;
return temp;
}
最佳答案
表达式 (d1 + d2)
在从 operator+ 返回时产生一个临时对象(return temp
)。从“temp”创建临时文件是通过复制构造函数完成的。然后将其分配给 d3。
关于c++ - 为什么在C++中调用d1=d2+d3语句的拷贝构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14495832/