vendredi 31 mars 2017

Copy constructor called instead of Operator= [duplicate]

I’m trying to do a simple exercise now with a Matrix and I want to implement this operations: Matrix a, Matrix b, Matrix c(a), Matrix d = a, Matrix e = a + b. For the moment I keep it simple but later I want to do the same thing, but with dynamic allocation and later with smart pointers.

I declared an explicit copy constructor and I overloaded operator=, I also declared a destructor so I have the rule of three.

Here are my functions:

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];
        }
    }
}

The problem is that, when I try to use Matrix d = a my compiler use the copy constructor, not my operator=.

Output:

Aucun commentaire:

Enregistrer un commentaire