c++ - 错误 : no match for ‘operator<’ when I stream to cout

标签 c++

我正在创建一个 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/

相关文章:

c++ - 大型缓冲区与大型静态缓冲区,有优势吗?

C++:什么更快 - 在 hashmap 或 switch 语句中查找?

c++ - 使用 std::sort 对字符串进行排序,使大写字母位于小写字母之后

c++ - 使用 GDI 创建 8bpp 位图并将其保存为文件

c++ - a+b+c<=n的解数

c++ - 使用 Boost::asio 触发写入

c++ - 动态数组类,程序运行良好但出现错误

c++ - 无论如何检测到 valgrind 泄漏

c++ - 如何将一年中的某一天 (1-365) 转换为其等效日期(即 2013 年 1 月 5 日)C++

c++ - 在 Windows 10 上使用 minGW 运行 SFML C++ 程序