0

我有类,它的行为类似于矩阵,并且那里的所有操作(如+,-等)都运行*良好。但是当我尝试获取单个值时,我会得到奇怪的值,例如 2.08252e-317 ...我'已经意识到,只有当我想以这种方式创建新的 metrix 时才会发生此错误:

const Matrix b = a ;

没有const它工作得很好......

这是我班级的声明:

class Matrix {
public:

Matrix(int x, int y);
~Matrix(void);
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;

class Proxy {
    Matrix* _a;
    const Matrix* _constA;
    int _i;
public:

  Proxy(Matrix& a, int i) : _a(&a), _i(i) {
    }

    Proxy(const Matrix& constA, int i) : _constA(&constA), _i(i) {
    }

    double& operator[](int j) {
        return _a->_arrayofarrays[_i][j];
    }
};

Proxy operator[](int i) {
    return Proxy(*this, i);
}

Proxy operator[](int i) const {
    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;
};

 //constructor

 Matrix::Matrix(int x, int y) {
_arrayofarrays = new double*[x];
for (int i = 0; i < x; ++i)
    _arrayofarrays[i] = new double[y];
this->x = x;
this->y = y;
}  

所以我创建了一些实例,用值填充它,然后,当我想在某个索引上打印值时,我得到了那些奇怪的值:-/

IE:

Matrix a(3,5);
//fill in the values to a
cout << a[1][1] << endl // prints out some nonsence

有谁知道如何重写这个类以获得正确的值?

4

0 回答 0