Simple Matrix类,错误:调用私有构造函数

时间:2017-12-20 23:22:28

标签: c++ matrix

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

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

问题:为什么会这样?我如何理解失败的原因?有人能指出我的解决方案/阅读材料,以帮助我理解这个问题。谢谢你的帮助!

1 个答案:

答案 0 :(得分:2)

默认情况下,对类的属性/方法的访问是私有的。在您的课程中添加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();
}
相关问题