class Time
{
public:
Time(int h = 0, int m = 0, int s = 0) : hour(h), min(m), sec(s) {}
void SetTime(int h, int m, int s);
friend ostream& operator << (ostream& os, const Time& t);
private:
int sec, min, hour;
};
void Time::SetTime(int h, int m, int s) {
hour = h, min = m, sec = s;
}
ostream& operator << (ostream& os, const Time& t) {
os << t.hour << ':' << t.min << ':' << t.sec;
return os;
}
将重载函数设置为友元函数可以操控类的私有成员
Time t(1, 2, 3);
cout << t;
会输出 1:2:3;