使用一個構造函數和操作符重載的作品與我的目標如下創建零的2×4矩陣:如何使用靜態成員函數創建矩陣,然後使用運算符重載打印該矩陣?
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;
的原因,我需要保持數據的變量,因此可以在運營商< <重載函數中使用正如之前爲構造函數所做的那樣。然而,在我的靜態成員函數中嘗試了幾種不同的變體之後,我沒有像以前那樣容易地將我的矩陣存儲在數據變量中。有人有任何建議嗎?
我已經在simila實現了它你如何寫在這裏。雖然'Matrix Matrix :: Ones(const int noOfRows,const int noOfCols)Matrix outO(noOfRows,noOfCols,1); return outO; }' 這使用我的構造函數,然後我可以在我的原始帖子中使用我的代碼來使用運算符<< overloading – MachoSkinny
好。不要忘記三條規則,以防止在操作Matrix類時出現崩潰。 – jpo38