我有以下用于定义Matrix类的代码。头文件中的定义如下:
#ifndef MATRIX_H
#define MATRIX_H
/* General matrix class */
class Matrix
{
public:
Matrix(int m, int n, double ini);
virtual ~Matrix();
Matrix(const Matrix& other); //copy ctor
Matrix& operator=(const Matrix& other); //assignment operator;
double operator()(int i, int j) const; //access element in the matrix
double& operator() (int i, int j); //set element in the matrix
friend Matrix operator+(const Matrix& mat1, const Matrix& mat2); //Matrix addition
friend Matrix operator+(const Matrix& mat1, double a); //scaler multiplication
int dimension() const {return rows*cols;} //getter method for dimension
protected:
private:
int rows; //number of rows in the matrix
int cols; //number of cols in the matrix
double* d; //pointer to the representation of the matrix
};
与问题相关的部分的实施如下所示。
#include "Matrix.h"
#include<iostream>
Matrix::Matrix(int m, int n, double ini):rows{m},cols{n},d{new double[m*n]}
{
//ctor
double* p = d;
for(int i=0;i<rows*cols;i++)
{
*p++ = ini;
}
}
Matrix::~Matrix()
{
//dtor
delete []d;
}
Matrix& Matrix::operator=(const Matrix& rhs)
{
if (this == &rhs) return *this; // handle self assignment
if (rows*cols<=rhs.rows*rhs.cols)
{
delete []d;
d = new double[rhs.rows*rhs.cols];
rows = rhs.rows;
cols = rhs.cols;
for(int i=0;i<rows*cols;i++)
{
d[i] = rhs.d[i];
}
}
//assignment operator
return *this;
}
double Matrix::operator()(int i, int j) const
{
return d[rows*i + j];
}
double& Matrix::operator()(int i, int j)
{
return d[rows*i+j];
}
现在,我有一个简单的测试应用程序,它创建一个矩阵,为矩阵中的元素赋值,同时读取元素的值(给定行和列号)。
#include <iostream>
#include "Matrix.h"
using namespace std;
int main()
{
int i,j;
Matrix A(3,2,0.0);
cout<<A.dimension()<<endl;
// assign values to matrix elements
for (i=0;i<3;i++)
{
for (j=0;j<2;j++) A(i,j) = 0.1*i*j;
}
// access matrix elements
double sum = 0.0;
for (i=0;i<3;i++) {
for (j=0;j<2;j++) sum += A(i,j); }
cout << "The sum of the matrix elements is ";
cout << sum << endl;
return 0;
}
我的问题是,虽然一切都没有问题编译,但在运行时,主要功能会冻结 - &#34;总和&#34;以上是计算的。想知道这是否是由于析构函数未被调用或无法被调用。非常感谢,如果有人有任何想法。
答案 0 :(得分:1)
我认为你的代码在operator()
中是错误的double Matrix::operator()(int i, int j) const
{
return d[cols*i + j];
}
double& Matrix::operator()(int i, int j)
{
return d[cols*i+j];
}
你溢出了数组d []