I want to overload << and >>

I'm trying to remember how to stream my class to an fstream.
[code]
say class a{

int x;
int y;
ostream& operator << (ostream os,class a){
os << a.x;
os << a.y;
return os;
}

Any help or ref to readings appreciated.
If your members are accessable from outside the class no problem
1
2
3
4
5
6
7
8
9
10
11
class A
{
public:
    int x, int y;
};

// Outside of class:
std::ostream& operator<< (std::ostream& os, const A& a)
{
    return (os << a.x << ' ' << a.y);
}


Otherwise you have two options:
a) make operator<<(const ostream& os, const A& a) a friend function
b) make getter functions.

making it a friend
1
2
3
4
5
6
7
8
9
10
11
12
class A
{ 
    friend std::ostream& operator<< (std::ostream& os, const A& a);
private:
    int x, int y;
};

// Outside of class:
std::ostream& operator<< (std::ostream& os, const A& a)
{
    return (os << a.x << ' ' << a.y);
}


providing getters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class A
{ 
public:
    int getX() const { return x; }
    int getY() const { return y; }
private:
    int x, int y;
};

// Outside of class:
std::ostream& operator<< (std::ostream& os, const A& a)
{
    return (os << a.getX() << ' ' << a.getY());
}
Last edited on
Thank you, that will work. :)
Topic archived. No new replies allowed.