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

标签 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(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::Zeros(const int noOfRows, const int noOfCols){
    Matrix out;
    for(int i=0; i< noOfRows; i++){
        for(int j=0; j<noOfCols; j++){
           int index = i*noOfCols + j;
           out.data[index]=0;
        }
    }
}

我不确定我是否正确地实现了静态成员函数,我的问题是在我的头函数中我需要使用以下变量:

int noOfRows;
int noOfColumns;
double *data;
int GetIndex(const int rowIdx, const int columnIdx) const;

在我的测试文件中,我想按如下方式实现这个静态成员函数:

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

我需要保留数据变量的原因是它可以在 operator<< 重载函数中使用,因为它以前用于构造函数。但是,在我的静态成员函数中尝试了几种不同的变体后,我并没有像以前那样轻松地将矩阵存储在数据变量中。有人有什么建议吗?

最佳答案

所以,我看到您的静态函数显然首先执行此操作。

Matrix output;

但是,您显示的构造函数代码有两个参数,即行数和列数。

据此,我必须得出结论,您还必须有一个默认构造函数,它可能构造一个空矩阵,带有一个空的 data。 vector 。

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

然后,这里尝试初始化默认构造矩阵的内容,而没有有效初始化 data成员(member)。

这不会有好结果...

P.S.,你可能也想读这个:RAII .我怀疑您的类(class)在这方面也会有相关问题。而不是使用 double *data成员(member),一个std::vector<double>会更好地工作,并且很可能会避免这方面的一系列陷阱。

关于c++ - 如何使用静态成员函数创建一个矩阵,然后可以使用运算符重载打印该矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34584138/

相关文章:

c++ - 头文件 C/C++ 中的符号

c++ - 从偏移位置开始复制内存

python - 如何搜索矩阵中的连通元素?

为 cout 取消引用指针时的 C++ SegFault

c - 当尝试从 bmp 文件中提取 RGB 分量时,为什么我的代码段出现错误?

c++ - 如何在 C++ 中将 std::string 值传递给 RegSetValueEx()

c# - native C++/MFC 所需的 C# 的 PreviewKeyDown 等效项

c++ - 来自线性化矩阵 CUDA 的唯一行

java - 从任何类读取和写入的矩阵

c - 添加元素时链接列表出现段错误