我分别在person与student类中都以友元函数重载了<< 期望看到的结果是当进行到cout<<stu.teacher时自动调用person类中的<<重载函数,可是却显示<<不能作用于person类(VS报的),而单独调用却可以。
想请问问什么会出现这种错误以及如何补救。
#include<iostream>
using namespace std;
class person {
string name;
public:
person(string n) :name(n) {};
friend ostream& operator<<(ostream& os, person& per);
};
class student :public person {
person teacher;
int score;
public:
student(string n, string n_teacher, int s)
:person(n), teacher(n_teacher), score(s) {};
friend ostream& operator<<(ostream& os, student& stu);
};
ostream& operator<<(ostream& os, person& per)
{
os<< "name:" << per.name << endl;
return os;
}
ostream& operator<<(ostream& os, student& stu)
{
os << "the student:" << endl;
os << stu.name;//父类私有成员对子类不可见,此语句也无法实现。
os << "score:" << stu.score << endl;
os >> stu.teacher;//我明明在person类里定义了友元函数重载<<了,可这里还是不对。
return os;
}
int main()
{
student s1("Zhang San", "Li Si", 98);
cout << s1;//不可行
person p1("ff");//可行
cout << p1;
return 0;
}