如果它们适合添加,我真的不知道如何检查两个矩阵的大小。 这是我的代码,目前正在运行,没有错误:
matrix operator+(const matrix & mat){
matrix add;
add.mSize = mat.mSize;
add.mP = new int[add.mSize * add.mSize];
for(int i = 0; i < add.mSize * add.mSize; i++){
add.mP[i] = mP[i] + mat.mP[i];
}
return add;
}
答案 0 :(得分:1)
一般的2d矩阵有两个不同的维度,行和列(除非它是方阵的特殊情况)。
在一般情况下,您的代码可能是:
#include <stdexcept>
class matrix
{
public:
matrix(int rows, int columns) :
mRows(rows), mColumns(columns), mP(NULL)
{
mP = new double[mRows * mColumns];
for (int i = 0; i < mRows * mColumns; i++)
mP[i] = 0.0;
}
matrix(const matrix& other) :
mRows(other.mRows), mColumns(other.mColumns), mP(NULL)
{
mP = new double[mRows * mColumns];
for (int i = 0; i < mRows * mColumns; i++)
mP[i] = other.mP[i];
}
~matrix()
{
delete[] mP;
}
const double* operator[] (int row) const {
return &mP[row * mColumns];
}
double* operator[] (int row) {
return &mP[row * mColumns];
}
matrix& operator=(const matrix& other) {
if (this == &other) return *this;
if ((mRows != other.mRows) || (mColumns != other.mColumns)) throw std::invalid_argument( "dimensions don't match" );
for (int r = 0; r < mRows; r++) {
for (int c = 0; c < mColumns; c++) {
(*this)[r][c] = other[r][c];
}
}
return *this;
}
matrix& operator+=(const matrix& other) {
if ((mRows != other.mRows) || (mColumns != other.mColumns)) throw std::invalid_argument( "dimensions don't match" );
for (int r = 0; r < mRows; r++) {
for (int c = 0; c < mColumns; c++) {
(*this)[r][c] += other[r][c];
}
}
return *this;
}
private:
int mRows;
int mColumns;
double *mP;
};
inline matrix operator+(matrix lhs, const matrix& rhs)
{
lhs += rhs;
return lhs;
}