我已经上课了,表示lika是一个矩阵,而+
,-
,*
之类的所有操作都运行良好..但是当我想要获得时单个值,然后我得到奇怪的值,如2.08252e-317 ......
我已经意识到,当我想以这种方式创建新的metrix时,这个bug只会发生:
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;
}
所以我创建了一些实例,用值填充它然后,当我想在某个索引上打印值时,我得到那些奇怪的值: - /
即:
Matrix a(3,5);
//fill in the values to a
cout << a[1][1] << endl // prints out some nonsence
有没有人知道,如何重写这个类才能获得正确的值?