简单矩阵类,错误:调用私有构造函数

Simple Matrix class, error: calling private constructor

本文关键字:调用 构造函数 错误 简单      更新时间:2023-10-16

我正在学习C++并尝试构建一个简单的矩阵类。我的基本情况将矩阵类定义为:

class Matrix {
int r; // number of rows
int c; // number of columns
double* d; // array of doubles to hold matrix values
Matrix(int nrows, int ncols, double ini = 0.0);
~Matrix();
}

构造函数/析构函数是:

Matrix::Matrix(int nrows, int ncols, double ini) {
r = nrows;
c = ncols;
d = new double[nrows*ncols];
for (int i = 0; i < nrows*ncols; i++) d[i] = ini;
}
Matrix::~Matrix() {
delete[] d;
}

问题:当我通过调用Matrix my_matrix(2,3)实例化类 Matrix 时,出现以下错误:error: calling a private constructor of class 'Matrix'error: variable of type 'Matrix' has private destructor

问:为什么会这样?我如何理解什么是失败?有人可以指出我的解决方案/阅读材料来帮助我理解这个问题。感谢您的帮助!

默认情况下,对类的属性/方法的访问是私有的。在类中添加public:语句:

class Matrix {
int r; // number of rows
int c; // number of columns
double* d; // array of doubles to hold matrix values
public:    
Matrix(int nrows, int ncols, double ini = 0.0);
~Matrix();
}