I don't understand: "friend std::ostream & operator<<(std::ostream & out, const Hour & h);"

I have to define methods of a given class:
Hour.h
1
2
3
4
5
6
7
8
9
10
11
...
class Hour{
public: 
	Hour();
	friend std::ostream & operator<<(std::ostream & out, const Hour & h);

private:
	unsigned int h_hour;
	unsigned int h_min;
	unsigned int h_sec;
};


And my code:
Hour.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
...
Hour::Hour()
{
	h_hour=0;
	h_min=0;
	h_sec0;
}

inline ostream& operator<<(ostream& out, const Hour& h) {
//???
//???
}
...


What exactly am I suppose to code? Actually, I don't know what to code because I don't know what this method is actually suppose to do.

I know it's a bit operator. I'm not sure what ostream is or why he's needed.

Thank you.
1
2
3
4
inline ostream& operator<<(ostream& out, const Hour& h) {
//???
//???
}


Should be :
1
2
3
4
5
inline ostream& operator<<(ostream& out, const Hour& h) 
{
    out << h.getHour() << ' ' << h.getMinute() << ' ' << h.getSecond();
    return out;
}

> I'm not sure what ostream is or why he's needed.
https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx

Normally, if you want to print attributes of your own class in a certain format, you'd have to do this (I'm going to follow SakurasouBusters and assume that you have accessors defined in your class).
1
2
3
4
5
6
7
8
int main()
{
    Hour myHour;
    Hour yourHour;

    std::cout << myHour.getHour() << ' ' << myHour.getMinute() << ' ' << myHour.getSecond() << std::endl;
    std::cout << yourHour.getHour() << ' ' << yourHour.getMinute() << ' ' << yourHour.getSecond() << std::endl;
}


However, if you overload the <<operator as SakurasouBusters has shown. You can print the class object in this fashion.
1
2
3
4
5
6
7
8
int main()
{
    Hour myHour;
    Hour yourHour;

    std::cout << myHour << std::endl;
    std::cout << yourHour;
}


It removes a lot of code from your main function, so it looks neat. If you need to edit output formatting for this class, you can simply do it in the body of the overloaded <<operator instead of making numerous edits throughout the body of the main function.
Last edited on
Topic archived. No new replies allowed.