class Matrix
{
private:
int m_nrows;
int m_ncols;
double** m_data;
void init()
{
m_data = new double*[m_nrows];
for(int i = 0; i < m_nrows; i++)
m_data[i] = new double[m_ncols];
}
// clean up
void free()
{
if(m_data != NULL)
for(int i = 0; i < m_nrows; i++) delete [] m_data[i];
delete [] m_data;
}
public:
// constructor
Matrix(int nrows, int ncols):m_nrows(nrows), m_ncols(ncols) // Zeros
{
init();
for (int i = 0; i < nrows; i++)
for (int j = 0; j < ncols; j++)
m_data[i][j] = 0.0;
}
Matrix(int nrows, int ncols, const double *val):m_nrows(nrows), m_ncols(ncols) // Initialized by 1D Array
{
init();
for (int i = 0; i < nrows; i++)
for (int j = 0; j < ncols; j++)
m_data[i][j] = *val++;
}
//Operators =, +
Matrix & operator = (const Matrix &rhs)
{
if (this != &rhs){
if(m_nrows != rhs.m_nrows || m_ncols != rhs.m_ncols){
m_nrows = rhs.m_nrows;
m_ncols = rhs.m_ncols;
}
free();
init();
for (int i = 0; i < m_nrows; i++)
for (int j = 0; j < m_ncols; j++)
m_data[i][j] = rhs.m_data[i][j];
}
return *this;
}
Matrix operator + (const Matrix &rhs)
{
if (m_nrows == rhs.m_nrows && m_ncols == rhs.m_ncols ){
Matrix new_mat(m_nrows, m_ncols);
for (int i = 0; i < new_mat.m_nrows; i++)
for (int j = 0; j < new_mat.m_ncols; j++)
new_mat.m_data[i][j] = m_data[i][j] + rhs.m_data[i][j];
return new_mat;
}
else
std::cerr << "Operator '+' Matrix dimensions must agree";
}
};
int main()
{
double x[6] = { 1, 2, 3, 4, 5, 6};
Matrix a
Matrix b(2,3,x);
Matrix c(2,3,x);
a = c;
a.print();
std::cout<<std::endl;
c = a+b;
return 0;
}
您好,
此代码用于执行简单的2d矩阵运算。 但是,我只是无法让操作员“+”正确。 其余的代码在我的测试中是有效的。 有些不对劲,但我找不到它。 需要你的帮助!
显示错误消息 * glibc检测到* ./a.out:双重免费或损坏(输出):0x0000000001ec4160 ***。 要么 分段错误:11 使用不同的编译器。