先举个例子:
#include <iostream>
using namespace std;
class Student{
private:
int _a;
int _b;
public:
Student(int a, int b):_a(a), _b(b){}
friend ostream& operator <<(ostream& os, Student& s){
os << s._a << "--" << s._b;
return os;
}
};
class Graduate: public Student{
private:
int _c;
public:
Graduate(int a, int b, int c):Student(a, b), _c(c){}
};
int main()
{
Student s(1, 2);
cout << s << endl;
Graduate gra(3, 4, 5);
cout << gra << endl;
return 0;
}
输出结果为:
父类Student有一个输出流重载,可以看到子类Graduate可以利用隐式转换成父类Student,并调用了父类的友元函数,最终的输出格式跟父类一样。那如果子类想输出从父类继承的东西还有自己的东西,就得重载operator<<这个全局函数:
#include <iostream>
using namespace std;
class Student{
private:
int _a;
int _b;
public:
Student(int a, int b):_a(a), _b(b){}
friend ostream& operator <<(ostream& os, Student& s){
os << s._a << "--" << s._b;
return os;
}
};
class Graduate: public Student{
private:
int _c;
public:
Graduate(int a, int b, int c):Student(a, b), _c(c){}
friend ostream& operator<<(ostream& os, Graduate& gra){
cout << static_cast<Student&>(gra);
os << "--" << gra._c;
return os;
}
};
int main()
{
Student s(1, 2);
cout << s << endl;
Graduate gra(3, 4, 5);
cout << gra << endl;
return 0;
}
输出结果为:
这里只需要注意重载的函数里内,需要先将子类显示的转换成父类的引用(以为转换过程中会形成中间变量,而这个中间变量是个临时值,所以必须用引用来接收,或者将父类友元的参数类型改成:const Student& ),去调用父类的友元,因为子类不能直接访问父类的私有成员,最后再输出自己的东西就可以了。