【发布时间】:2013-01-24 07:15:14
【问题描述】:
我是 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;
}
【问题讨论】:
-
类型 d3; d3 = d1 + d2。这就是为什么我很难理解它。
-
你的
+运算符重载函数里面有什么?你能发布一下吗? -
复制构造函数用于构造
d1 + d2的(临时)返回值。 -
@DanielTaylor:欢迎来到 SO。请附上相关代码sn-ps,包括
operator=和operator+的声明。 -
谢谢,我已经添加了操作符。
标签: c++ copy-constructor