【问题标题】:Copy constructor called instead of Operator= [duplicate]调用复制构造函数而不是 Operator= [重复]
【发布时间】:2017-08-25 20:47:19
【问题描述】:

我现在尝试用一个矩阵做一个简单的练习,我想实现这个操作:矩阵 a,矩阵 b,矩阵 c(a),矩阵 d = a,矩阵 e = a + b。目前我保持简单,但后来我想做同样的事情,但使用动态分配,然后使用智能指针。

我声明了一个显式的复制构造函数并重载了 operator=,我还声明了一个析构函数,所以我有三个规则。

这是我的功能:

Matrix& Matrix::operator=(const Matrix& opEven)
{
    std::cout << "Operator = " << std::endl;
    for (int i = 0; i < ORD; i++)
    {
        for (int j = 0; j < ORD; j++)
        {
            arr1[i][j] = opEven.arr1[i][j];
        }
    }

    return *this;
}

Matrix::Matrix(const Matrix& obj) 
{
    std::cout << "Constructing matrix using copy c-tor." << std::endl;
    for (int i = 0; i < ORD; i++)
    {
        for (int j = 0; j < ORD; j++)
        {
            arr1[i][j] = obj.arr1[i][j];
        }
    }
}

问题是,当我尝试使用 Matrix d = a 我的编译器使用复制构造函数,而不是我的 operator=。

Output:

【问题讨论】:

    标签: c++ c++11 matrix operator-overloading copy-constructor


    【解决方案1】:

    当你这样称呼它时

    Martix a;
    Matrix b = a; 
    

    它总是使用复制构造函数。试试这个:

    Matrix a;
    Matrix b:
    b = a;
    

    基本上,Matrix a = b;Matrix a(b); 是一回事,因为您是使用矩阵 b构造矩阵 a,因此会导致复制构造函数调用。

    【讨论】:

    • 谢谢,现在可以了。但我必须将其称为 Matrix b = a 并作为 operator=
    • 嗯,c++就是这样工作的,当你的对象还没有被构造时,你不能让它使用赋值运算符。
    • @Teodor-MarianWolf 你不能。 Type name = something 形式的任何内容都将始终调用复制构造函数。这就是语言的工作原理。
    猜你喜欢
    • 1970-01-01
    • 2016-03-25
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 2012-06-28
    • 1970-01-01
    相关资源
    最近更新 更多