Using a constructor and operator overloading works as follows with my aim to create a 2x4 matrix of zeros:
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;
}
However when I try to use a static member function, I'm getting a segmentation fault for the following code (see below for implementation in test file):
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;
}
}
}
I'm unsure if I'm implementing the static member function correctly, my issue is that in my header function I need to use the following variables:
int noOfRows;
int noOfColumns;
double *data;
int GetIndex(const int rowIdx, const int columnIdx) const;
And in my test file, I want to implement this static member function as follows:
Matrix matrix = Matrix::Zeros(2,4);
cout<<matrix<<endl;
The reason I need to keep the data variable is so it can be used in the operator<< overloading function as it worked before for the constructor. However, having tried several different variations within my static member function I'm not having much luck with storing my matrix in the data variable as easily as before. Does anybody have any suggestions?