2015-08-14 58 views
2

我需要寫一個Matrix類,它有一個指向雙精度數組的指針。我需要以'矩陣方式'打印這些雙打。我做了一個引用數組的私有'double * m'(請參見構造函數)。現在,運營商< <是一個非成員函數,我不知道如何打印出數組,其中指針指向..非成員函數需要通過指針打印出一個數組

class Matrix { 
private: 
    double * m; 
    int size; 
public: 
    Matrix(const int rows = 2, const int columns = 2); 
    Matrix(const Matrix& matrix); 
    Matrix& operator=(const Matrix& matrix); 
    double * getM() const {return m;} 
    friend const Matrix& operator *(int x, const Matrix& m); 
    friend const Matrix& operator *(const Matrix& matrix,int x); 
    friend std::ostream& operator<<(std::ostream& out, const Matrix& matrix); 

    int getSize() const {return size;} 
    void setSize(const int s){size = s;} 
    virtual ~Matrix(); 
    }; 

    Matrix::Matrix(const int rows, const int columns) { 
      size = rows * columns; 
      m = new double[size]; 
      for(int i = 0; i < size; i++){ 
      *(m+(i+1)) = i+1; 
      } 
    } 

回答

1

既然你已經宣佈你operator <<一個你Matrixfriend ,運營商可以訪問所有matrix的私人會員,包括小指成員mint成員size。您可以充分利用他們在執行您的運營商:

std::ostream& operator<<(std::ostream& out, const Matrix& matrix) { 
    double *a = matrix.m; 
    int s = matrix.size; 
    ... 
    // Do printing here 
} 
+0

感謝您的答案。你知道爲什麼我的析構函數不起作用,我總是得到錯誤,他餵養未分配的數據。 (m){ \t delete m; \t} } – GNIUS

+0

@GNIUS很有可能是因爲你的拷貝構造函數或賦值操作符做錯了某件事(或者忘了做某件事)。你可能想要用你的構造函數的代碼發佈一個單獨的問題,以及產生錯誤的測試。 – dasblinkenlight