我将如何使用调用相同构造函数的静态成员函数创建两个矩阵(所有值为 Ones 或值 Zeros)?

How would I create two matrices (all values Ones or values Zeros) using static member functions which call the same constructor?

所以基本上我的程序使用静态成员函数请求 2x4 零点矩阵的工作方式如下:

Matrix Matrix::Zeros (const int noOfRows, const int noOfCols){
    Matrix outZ(noOfRows, noOfCols);
    return outZ;
} //My static Zeros member function

这是指我的构造函数,它在 2x4 矩阵中存储零值,如下所示:

Matrix::Matrix (const int noOfRows, const int noOfCols){

this->noOfRows = noOfRows;
this->noOfCols = noOfCols;

data = new double[noOfRows*noOfCols];
    for(int i=0; i< noOfRows*noOfCols; i++){
        data[i] = 0;
    }
}

我的问题是我想使用以下静态成员函数调用同一个构造函数来请求一个 2x4 矩阵:

Matrix Matrix::Ones(const int noOfRows, const int noOfCols){
    Matrix outO(noOfRows, noOfCols);
    return outO;
} //My static Ones member function

这显然是 returns 一个 2x4 矩阵,其中包含零而不是一。 因此,我一直在尝试找出一种方法在我的构造函数中使用 if 语句,以便它将根据我在静态成员函数中返回的对象名称创建一个零或一个矩阵,即

if(outZ){
    for(int i=0; i< noOfRows*noOfCols; i++){
        data[i] = 0;
    }
}

if(outO){
    for(int i=0; i< noOfRows*noOfCols; i++){
        data[i] = 1;
    }
}

这是否可能或是否有更好的替代方法来实现此 if 语句? (我在这种格式上受到限制,因为我需要使用数据变量,因为我稍后在 operator<< 重载期间使用它)

将值作为可选参数传递。

声明:

Matrix (const int noOfRows, const int noOfCols, int value = 0);

实施:

Matrix::Matrix (const int noOfRows, const int noOfCols, int value){
   ...
   data[i] = value;
   ...
} 

更改 Matrix::Ones 的实现以使用 1 作为最后一个参数。

Matrix Matrix::Ones(const int noOfRows, const int noOfCols){
    Matrix outO(noOfRows, noOfCols, 1);
    return outO;
}

PS 使用 const int 作为参数类型没有任何好处。您可以仅使用 int.

使您的代码更简单
Matrix (int noOfRows, int noOfCols, int value = 0);

同样的建议也适用于其他功能。