传递对象C ++的常量引用

时间:2014-04-25 15:28:25

标签: c++

这是我的代码:

#include <cstdlib>
#include <vector>
#include <iostream> 
#include <cstring>  

using namespace std;

class GeneralMatrix {
public:
    GeneralMatrix(const string & n, int nr, int nc);
    GeneralMatrix * add (const GeneralMatrix&);
    const double get(int row, int col){}
    void set(int row, int col, double val){}
};

GeneralMatrix * GeneralMatrix::add(const GeneralMatrix& m2){
if (height != m2.height || width != m2.width) {
            throw "Matrix sizes must match!";
        }
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                double val = m2.get(i, j);// Error
                if (val != 0) {
                    val += get(i, j);
                    set(i, j, val);
                }
            }
        }   
} 

int main(int argc, char** argv) {

    GeneralMatrix* a ;
    GeneralMatrix* b ;
    (*a).add(*b);
    return 0;
}

当我调用添加功能

时,我的程序会产生此错误
main.cpp:78:41: error: passing ‘const GeneralMatrix’ as ‘this’ argument of ‘const double GeneralMatrix::get(int, int)’ discards qualifiers [-fpermissive]
                 double val = m2.get(i, j);

所以问题在于持续的争论,但我无法弄清楚为什么。 get方法是常量,并不像add方法那样改变对象。

1 个答案:

答案 0 :(得分:7)

如果对象(或用于访问它的引用)是常量,那么您只能在其上调用常量成员函数。 get不是常数,但几乎可以肯定:

double get(int row, int col) const {}
                             ^^^^^

使返回值保持不变通常不是一个好主意,所以我删除了const

相关问题