Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overload the operator << inside a structure

Tags:

c++

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 "<<"?

like image 362
Dru01 Avatar asked Oct 19 '25 05:10

Dru01


1 Answers

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.

like image 190
Galik Avatar answered Oct 21 '25 19:10

Galik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!