Dru01
Dru01

Reputation: 95

How to overload the operator << inside a structure

I just want to print the two values of my structure, but can't compile my code - I get: no operator “<<” matches these operands.

#include <iostream>

using namespace std;

struct SCoor
{
    int i, j;

    bool operator == (const SCoor & tmp) const
    {
        return (i == tmp.i && j == tmp.j);
    }

    bool operator < (const SCoor & tmp) const
    {
        return (i < tmp.i || (i == tmp.i && j < tmp.j));
    }

    ostream& operator << (ostream &o) {
        return o << i << " " << j;
    }

};


int main()
{

        SCoor tmp = { 3, 3 };

    cout << tmp;

    return 0;
}

How do I have to overload the operator "<<"?

Upvotes: 4

Views: 1091

Answers (1)

Galik
Galik

Reputation: 48615

You overload the << operator as a member function if you want your structure to be on the left hand side of the expression. So:

struct SCoor
{
    // ...

    SCoor& operator << (Stuff const& s) {
        // ...
        return *this;
    }

};

// ...

Stuff stuff;
SCoor scoor;

scoor << s; // insert s into my SCoor

If you want to make your struct the right hand side of the << expression you have to define a standalone function:

std::ostream& operator<<(std::ostream& os, SCoor const& scoor)
{
    return os << scoor.i << " " << scoor.j;
}

However it is quite common to make the external function a friend function and to define it in the struct definition:

struct SCoor
{
    // ...

    friend std::ostream& operator<<(std::ostream& os, SCoor const& scoor)
    {
        return os << scoor.i << " " << scoor.j;
    }

};

// ...

SCoor scoor;

std::cout << scoor << '\n';

But it is not a member of your struct, it is just defined inside its definition for convenience.

Upvotes: 9

Related Questions