C++ 如何使用静态成员函数创建一个矩阵,然后使用运算符重载打印该矩阵?

C++ 如何使用静态成员函数创建一个矩阵,然后使用运算符重载打印该矩阵?,c++,matrix,segmentation-fault,operator-overloading,static-members,C++,Matrix,Segmentation Fault,Operator Overloading,Static Members,使用构造函数和运算符重载的工作原理如下,我的目标是创建一个2x4的零矩阵: Matrix::Matrix(const int noOfRowss, const int noOfCols){ this->noOfRows=noOfRowss; this->noOfColums=noOfCols; data= new double[noOfRows*noOfColumns]; for(int i=0; i< noOfRows; i++){ for(in

使用构造函数和运算符重载的工作原理如下,我的目标是创建一个2x4的零矩阵:

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

this->noOfRows=noOfRowss;
this->noOfColums=noOfCols;

data= new double[noOfRows*noOfColumns];

    for(int i=0; i< noOfRows; i++){
        for(int j=0; j<noOfColumns; j++){
           int index = i*noOfColumns + j;
           data[index]=0;
        }
    }
}

std::ostream& operator<<(std::ostream& output, const Matrix& rhs){
    for(int i=0; i< rhs.noOfRows; i++){
        for(int j=0; j<rhs.noOfColumns; j++){
            int index = i*rhs.noOfColumns + j;
            output<<rhs.data[index]<< "\t";
        }
        output<<std::endl;
    }
    return output;
}
在我的测试文件中,我想实现这个静态成员函数,如下所示:

Matrix matrix = Matrix::Zeros(2,4);
cout<<matrix<<endl;
矩阵=矩阵::零(2,4);

首先,我看到你的静态函数显然是这样做的

Matrix output;
但是,您显示的构造函数代码包含两个参数,行数和列数

由此,我必须得出结论,您还必须拥有一个默认构造函数,该构造函数可能构造一个空矩阵,其中包含一个空
数据
向量

for(int i=0; i< noOfRows; i++){
    for(int j=0; j<noOfCols; j++){
       int index = i*noOfCols + j;
       output.data[index]=0;
    }
}
for(int i=0;i对于(int j=0;j您需要指定
out
对象的大小,就像这样(否则,您正在填充
out.data
越界):

在头文件中,您可以有:

class Matrix
{
public:
     Matrix(const int noOfRowss, const int noOfCols, double defaultValue = 0);
     ...
};
然后:


std::我是否可以用与您在这里编写的类似的方式实现它。尽管
Matrix Matrix::one(const int noOfRows,const int noOfCols){Matrix outO(noOfRows,noOfCols,1);return outO;}
这将使用我的构造函数,然后我可以在我的原始帖子中实现我的代码,以使用运算符Good。不要忘记三条规则,以防止以后在操作
矩阵时崩溃。
for(int i=0; i< noOfRows; i++){
    for(int j=0; j<noOfCols; j++){
       int index = i*noOfCols + j;
       output.data[index]=0;
    }
}
Matrix Matrix::Zeros(const int noOfRows, const int noOfCols){
    Matrix out(noOfRows*noOfCols); // changed here
    for(int i=0; i< noOfRows; i++){
        for(int j=0; j<noOfCols; j++){
           int index = i*noOfCols + j;
           out.data[index]=0;
        }
    }
}
Matrix::Matrix(const int noOfRowss, const int noOfCols, double defaultValue)
{
    this->noOfRows=noOfRowss;
    this->noOfColums=noOfCols;

    data= new double[noOfRows*noOfColumns];

    for(int i=0; i< noOfRows; i++){
        for(int j=0; j<noOfColumns; j++){
           int index = i*noOfColumns + j;
           data[index]=defaultValue;
        }
    }
}
class Matrix
{
public:
     Matrix(const int noOfRowss, const int noOfCols, double defaultValue = 0);
     ...
};
std::cout << Matrix(4,2) << std::endl; // displays a 4x2 matrix filled with zeros
std::cout << Matrix(4,2,1) << std::endl; // displays a 4x2 matrix filled with ones