【问题标题】:copy constructor error: the object has type qualifiers that are not compatible with the member function复制构造函数错误:对象具有与成员函数不兼容的类型限定符
【发布时间】:2015-04-09 07:12:12
【问题描述】:

我正在使用简单的二维数组,但在我的复制构造函数中我遇到了一个问题。 这是我的代码的摘录:

//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&amp; obj) 传递。 我该怎么办?

【问题讨论】:

    标签: c++ matrix copy-constructor


    【解决方案1】:

    那是因为你的复制构造函数带有一个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
    

    【讨论】:

    • 谢谢。问题解决了。只是想知道当用于阅读的const 时它到底做了什么。
    • 在方法原型的末尾放一个const 禁止你修改你的类的属性,或者调用其他非const方法。但这意味着您的方法不会修改实例,因此它将允许您在 const 实例上调用您的方法,就像您的复制构造函数参数一样。所以把它放在任何可以放的地方,比如放在任何 getter 上。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2014-08-31
      • 2016-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      相关资源
      最近更新 更多