对于输出运算符"<<"的重载,除了写成这样的友元函数直接访问数据可以,如果把重载函数写到类外面该怎么写??

DONOT_LAUGH 2020-06-04 10:16:57
#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;
}
...全文
244 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
遇见女神 2020-06-07
  • 打赏
  • 举报
回复
普通函数重载就加个public方法访问private成员。
大雾 2020-06-06
  • 打赏
  • 举报
回复
如果要访问private成员,类里边还是要声明一下友元,类外边写定义。
DONOT_LAUGH 2020-06-04
  • 打赏
  • 举报
回复
我这样写到外面就有错了,应该怎么改?

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧