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

Pas*_*stx 2 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;
}
Run Code Online (Sandbox Code Playgroud)

当我调用add函数时,我的程序产生了这个错误

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);
Run Code Online (Sandbox Code Playgroud)

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

Mik*_*our 7

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

double get(int row, int col) const {}
                             ^^^^^
Run Code Online (Sandbox Code Playgroud)

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