对于输出运算符"<<"的重载,除了写成这样的友元函数直接访问数据可以,如果把重载函数写到类外面该怎么写??
#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
Student(int x = 0, string s = "NULL")
{
age = x;
xuehao=name = xingbie = address = yuanxi = s;
}
Student(string a,string b,string c,string d,string e,string f)
{
xuehao = a, age = c;
name = b, xingbie = d, address = e, yuanxi = f;
}
void display()
{
cout << "xuehao=" << xuehao << " yuanxi=" <<yuanxi<< endl;
cout << "name=" << name << " xingbie=" << xingbie << " age=" <<age<< endl;
cout << "address=" << address << endl;
}
private:
string xuehao,name, age,xingbie, address, yuanxi; //学号,姓名,年龄,性别,地址,院系;
};
class PostGraduate :public Student
{
public:
PostGraduate(string s = "NULL")
{
tutor = research = allowance = s;
}
PostGraduate(string a,string b,string c)
{
tutor = a, allowance = b, research = c;
}
void display()
{
cout << "tutor=" << tutor << endl;
cout << "research=" << research << endl;
cout << "allowance=" << allowance << endl;
}
friend ostream &operator<<(ostream &output, const PostGraduate &item)
{
output << "重载:" << endl;
output << "导师:"<<item.tutor << " " <<"研究方向:"<< item.allowance << " " <<"津贴:"<< item.tutor;
return output;
}
private:
string tutor, research, allowance; //导师,研究方向,津贴;
};
int main()
{
Student s1("20190001", "Michael", "19", "Male", "机场路10号","Computer Science");
s1.display();
PostGraduate p1("Liu", "1000", "Deep Learning");
p1.display();
cout << p1 << endl;
return 0;
}