2014-10-18 164 views
-4

错误我试图超载< <并使用标准'cout < < m1;'打印类型线。<< <<超载

// Output 
void Matrix::print(ostream& out) const 
{ 
    for(int i = 0; i < rows; i++) 
    { 
     for (int j = 0; j < cols; j++) 
     out << setw(4) << (*this)(i,j); 
     out << endl; 
    } 
} 

// Overloaded stream insertion operator 
ostream& operator<<(ostream& out, const Matrix& x) // display the matrix 
{ 
    return x.print(out); 
} 

我得到非const等等等等的无效初始化...

回答

2

这是一个非常简单的错误。请注意,您的operator<<函数声明它的返回值为ostream&,但您的Matrix::print方法没有任何回报。要解决此问题,请将您的operator<<功能更改为:

ostream& operator<<(ostream& out, const Matrix& x) // display the matrix 
{ 
    x.print(out); 
    return out; 
}