方法一:
class Date{
int year, month;
public:
Date(int Y, int M):year(Y), month(M){}
friend ostream& operator<<(ostream &o, const Date &d);
};
inline ostream& operator<<(ostream &o, const Date &d){
return (o << d.year << '-' << d.month);
}
方法二:
class Date{
int year, month;
public:
Date(int Y, int M):year(Y), month(M){}
ostream& output(ostream &o) const {
return (o << year << '-' << month);
}
};
inline ostream& operator<<(ostream &o, const Date &d){
return d.output(o);
}
方法一较方便,但破坏了类的封装性,允许外部函数访问类的私有成员。且当 Date 作为基类时无法保持输出的多态性
方法二稍麻烦,但不存在以上两个缺点。条件允许时尽量使用方法二