2015-08-27 34 views
-1

我目前正在編程一個int矩陣cpp。CPP | std流打印錯誤

我想補充一點,打印以下列方式的數字打印功能:

1 2 3 
7 6 9  
19 23 9 

(每2個intergers被分隔了空間,在該行沒有空間的結尾)。 所以我寫了下面的代碼:

std::ostream& IntMatrix::operator << (std::ostream& out) const 
{ 
    for(int i = 0; i < this->num_row; i++) 
    { 
      int j; 
      for(j = 0; j < this->num_col - 1; j++) 
      { 
        out << this->mat[i][j] << " "; 
      } 
      out << this->mat[i][j] << endl; 
    } 
    return out; 
} 

它是文件IntMatrix.cpp英寸然而 ,每次我試圖編譯代碼時,這是發生了什麼:

error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&' 

怎麼辦?

+0

使用全局運算符重載。 –

+1

不管那個錯誤,嘗試實現一個自由​​函數'ostream&operator <<(ostream&,const IntMatrix&)'而不是成員'ostream&IntMatrix :: operator <<(ostream&)const':成員操作符必須被調用爲'matrix << std :: cout',這是...不尋常的,可能不是你想要的。另請參閱[運算符重載常見問題解答](http://stackoverflow.com/q/4421706/1521179),瞭解有關實現運算符的提示。 – amon

回答

0

而是一個類的成員函數的使用過載的全局命名空間:

std::ostream& operator << (std::ostream& out, const IntMatrix& m) { 
} 

,並宣佈一個作爲IntMatrixfriend