简体   繁体   中英

copy constructor error: the object has type qualifiers that are not compatible with the member function

im working with simple 2D array,but in my copy constructor i encounter a problem. Here's a excerpt from my code:

//default constructor
Matrix::Matrix(int r, int c)
{
    rows = r;
    cols = c;
    mainArray = new int[rows*cols];
    array = new int *[rows];
    for (int i = 0; i < rows; i++)
        array[i] = mainArray + (i*cols);
}
//at member
int& Matrix::at(int i, int j)
{
    return array[i][j];
}
//copy constructor 
Matrix::Matrix(const Matrix & obj)
{
    rows = obj.rows;
    cols = obj.cols;
    mainArray = new int[rows*cols];
    array = new int *[rows];
    for (int i = 0; i < rows; i++)
        array[i] = mainArray + (i*cols);
    }
    for (int i = 0; i < obj.rows; i++)
    {
        for (int j = 0; j < obj.cols; j++)
            at(i, j) =obj.at(i,j);//PROBLEM
    }
}

when im trying to assign at(i,j)=obj.at(i,j) i get this: the object has type qualifiers that are not compatible with the member function

as far as i know, copy constructor is supposed to be passed by (const class& obj) . what should i do?

That's because your copy constructor take a const parameter, and your method Matrix::at is not const.

I suggest you to do two versions of your at method, one const and one not :

// Use for assignement
int& Matrix::at(int i, int j)
{
    return array[i][j];
}

// Use for reading
int Matrix::at(int i, int j) const
{
    return array[i][j];
}

Your compiler should know in which case call which one without your help, depending if you are trying to modify or just read your instance :

Matrix matrix(4, 4);

matrix.at(1, 2) = 42; // Assignement method called
int i = matrix.at(1, 2); // Read method called

Realize two versions of at function, one const and one non-const .

int& Matrix::at(int i, int j)
{
    return array[i][j];
}

int Matrix::at(int i, int j) const
{
    return array[i][j];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM