![](/img/trans.png)
[英]Object has type qualifiers that are not compatible with the member function
[英]copy constructor error: the object has type qualifiers that are not compatible with the member function
我正在使用简单的2D数组,但在我的复制构造函数中遇到问题。 这是我的代码的摘录:
//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
}
}
当我试图分配at(i,j)=obj.at(i,j)
我得到这个:该对象具有与成员函数不兼容的类型限定符
据我所知,复制构造函数应该由(const class& obj)
传递。 我该怎么办?
那是因为您的复制构造函数采用const
参数,而您的Matrix::at
方法不是const。
我建议您使用at
方法的两个版本,一个是const,另一个不是:
// 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];
}
您的编译器应该在没有您帮助的情况下知道哪种情况下调用哪个,这取决于您是试图修改还是只是读取实例:
Matrix matrix(4, 4);
matrix.at(1, 2) = 42; // Assignement method called
int i = matrix.at(1, 2); // Read method called
实现at
函数的两个版本,一个const
和一个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];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.