Mohsin Mushtaq
Mohsin Mushtaq

Reputation: 93

error: no match for ‘operator<’ when I stream to cout

I am creating a Matrix class, and I am overloading all of the basic operators. For instance:

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.


};

I also wrote a 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;
}

However, when I try to use these:

int main() {
     Matrix M1;
     cout << M1 < 5.8;
}

I get this error:

error: no match for ‘operator<’ in ‘operator<<((* & std::cout), (*(const Matrix*)(& m))) < 5.7999999999999998e+0

What does this error mean?

Upvotes: 2

Views: 82

Answers (1)

QuestionC
QuestionC

Reputation: 10064

The left-streaming operator << has higher precedence than the comparison operator <.

So...

cout << M1 < 5.8

is equivalent to

(cout << M1) < 5.8

http://en.cppreference.com/w/cpp/language/operator_precedence


PS. This behavior is dumb but we're stuck with it for historical reasons. The original intention of the << was to be a mathematical operation (where this precedence makes sense), not streaming.

Upvotes: 6

Related Questions