为什么在这里调用复制构造函数?

Tan*_*gar 2 c++ visual-c++ c++11 c++14

#include <iostream>
using namespace std;
class A
{
    int x;
public:

    A(int a)
    {   
        x = a;
        cout << "CTOR CALLED";
    }
    A(A &t)
    {
        cout << "COPY CTOR CALLED";
    }
    void display()
    {
        cout << "Random stuff";
    }
    A operator = (A &d)
    {   
        d.x = x;
        cout << "Assignment operator called";
        return *this;
    }
};

int main()
{
    A a(3), b(4);
    a = b;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

此代码的输出是:

CTOR CALLED
CTOR CALLED
分配操作员称为
COPY CTOR CALLED

当我在visual studio中使用手表时,它表明即使在调用重载赋值运算符之前,xin 的值a也已更改.

那么为什么复制构造函数甚至在这里被调用?

Som*_*ude 6

因为您从赋值运算符返回.它应该返回一个引用:

A& operator = (A &d) { ... }
Run Code Online (Sandbox Code Playgroud)

  • 只需注意参数应为const ref`A&operator =(A const&d){...}`复制构造函数相同. (6认同)
  • 而且你想以其他方式复制`x`的值.即`x = dx;` (3认同)