c++ - 为什么在C++中调用d1=d2+d3语句的拷贝构造函数?

标签 c++ copy-constructor

我是 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/

相关文章:

java - 在 C++ 中实现异常类

c++ - 构造函数 Foo::Foo 接收到对 Foo 的引用但不是复制构造函数

c++ - 如果删除了复制赋值运算符,为什么 MSVC 12.0 会忽略私有(private)构造函数?

c++ - 如何使用 CreateProcess 执行简单的命令行?

C++ 复制构造函数签名 : does it matter

c++ - 在结构的 STL 映射中,为什么 "[ ]"运算符会导致结构的 dtor 被额外调用 2 次?

c++ - 删除还是不删除(调用函数)?

c++ - 如何在不知道名称的情况下访问结构体成员?

c++ - C++中两个堆栈的有效表示?

c++ - 为什么 getline 跳过第一行?