无法为我的自定义类的对象赋值,该值的行为应类似于矩阵

Can't assign a value to object of my custom class, that shall behave like a matrix

本文关键字:类似于 赋值 我的 自定义 对象      更新时间:2023-10-16

我有自定义类,它的行为像矩阵。除了从同一类的其他实例赋值之外,一切都运行良好。

我可以这样写:

Matrix a(5,7);
// du stuff with a
Matrix b(5,7);
Matrix d=a+b;
d=a*5;
d[3][2]=1;
//but I can't do this:
double x=d[3][2];
//at this point I get this error:

main.cpp:604:12: error: passing ‘const Matrix’ as ‘this’ argument of ‘Matrix::Proxy Matrix::operator[](int)’ discards qualifiers

有没有人知道如何解决这个问题?(

矩阵类的实现在这里:

class Matrix {
public:
Matrix(int x, int y);
~Matrix(void);
//overloaded operators
Matrix operator+(const Matrix &matrix) const;  
Matrix operator-() const;
Matrix operator-(const Matrix &matrix) const; 
Matrix operator*(const double x) const; 
Matrix operator*(const Matrix &matrix) const; 
friend istream& operator>>(istream &in, Matrix& a);
class Proxy {
    Matrix& _a;
    int _i;
public:
    Proxy(Matrix& a, int i) : _a(a), _i(i) {
    }
    double& operator[](int j) {
        return _a._arrayofarrays[_i][j];
    }
};
Proxy operator[](int i) {
    return Proxy(*this, i);
}
// copy constructor
Matrix(const Matrix& other) : _arrayofarrays() {
    _arrayofarrays = new double*[other.x ];
    for (int i = 0; i != other.x; i++)
        _arrayofarrays[i] = new double[other.y];
    for (int i = 0; i != other.x; i++)
        for (int j = 0; j != other.y; j++)
            _arrayofarrays[i][j] = other._arrayofarrays[i][j];
    x = other.x;
    y = other.y;
}
int x, y;
double** _arrayofarrays;
};

您目前有一个operator[]签名:

Proxy operator[](Matrix *this, int i)

你想调用这个:

Proxy operator[](const Matrix *, int)

错误是说为了从const Matrix *转换到Matrix *, const必须被丢弃,这是不好的。您应该在类中提供const版本:

Proxy operator[](int) const {...}

在你的类中,它获得this的第一个参数,并且在参数列表之后的const意味着第一个参数将是一个指向你的类的常量对象的指针,而不是一个非常量对象。