我正在创建一个 Matrix 类,并且正在重载所有基本运算符。例如:
class Matrix {
Matrix operator<(const float& ); // returns a Matrix with
// entries 0 or 1 based on
// whether the element is less than
// what's passed in.
};
我还写了一个streaming operator:
ostream &operator<<(ostream&cout,const Matrix &M){
for(int i=0;i<M.rows;++i) {
for(int j=0;j<M.columns;++j) {
cout<<M.array[i][j]<<" ";
}
cout<<endl;
}
return cout;
}
但是,当我尝试使用这些时:
int main() {
Matrix M1;
cout << M1 < 5.8;
}
我收到这个错误:
error: no match for ‘
operator<
’ in ‘operator<<((* & std::cout), (*(const Matrix*)(& m))) < 5.7999999999999998e+0
’
这个错误是什么意思?
最佳答案
左流运算符 <<
优先级高于比较运算符 <
.
所以...
cout << M1 < 5.8
相当于
(cout << M1) < 5.8
http://en.cppreference.com/w/cpp/language/operator_precedence
附言。这种行为是愚蠢的,但由于历史原因,我们坚持使用它。 <<
的初衷是一个数学运算(这个优先级有意义的地方),而不是流媒体。
关于c++ - 错误 : no match for ‘operator<’ when I stream to cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29709265/