【问题标题】:Why is the copy constructor being called here?为什么在这里调用复制构造函数?
【发布时间】:2017-04-07 06:00:55
【问题描述】:
#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;
}

这段代码的输出是:

CTOR 被召唤
呼叫中心
赋值运算符称为
复制 CTOR 调用

当我在 Visual Studio 中使用手表时,它显示 a 中的 x 的值甚至在调用重载赋值运算符之前就已更改。

那么为什么还要在这里调用复制构造函数呢?

【问题讨论】:

    标签: c++ c++11 visual-c++ c++14


    【解决方案1】:

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

    A& operator = (A &d) { ... }
    

    【讨论】:

    • 请注意,参数应该是 const ref A&amp; operator = (A const &amp;d) { ... } 与复制构造函数相同。
    • 而您想以其他方式复制 x 的值。 IE。 x = d.x;
    【解决方案2】:

    正如@SomeProgrammerDude 已经说过的那样,这是因为您按值返回,而不是像通常使用赋值运算符那样按引用返回。我想补充一点,您的赋值运算符目前是错误的方法:

    A operator = (A &d)
    {   
        d.x = x;
        cout << "Assignment operator called";
        return *this;
    }
    

    通常你通过 const 引用传递d,因为我们想改变this 的成员。您正在更改d 的成员。这会在功能上将您的a = b; 变成b = a;,因为a = b; 现在实际上正在更改b 的成员!

    d 设置为const&amp; 可以防止这些错误。

    你应该把它改成:

    A& operator = (A const &d)
    {   
        x = d.x;
        cout << "Assignment operator called";
        return *this;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多