Ex9_A.cpp
上传用户:wuzhousb
上传日期:2022-07-12
资源大小:380k
文件大小:1k
- #include<iostream>
- #include<fstream>
- #include<string>
- using namespace std;
- class Person{
- string name; //姓名
- char sex; //性别
- public:
- Person(string n="noname",char s='m'){ //构造函数
- name=n;
- sex=s;
- }
- friend ostream& operator<<(ostream& dest,Person& ps);//输出姓名、性别
- };
- ostream& operator<<(ostream& dest,Person& ps){
- dest<<ps.name<<'t'<<ps.sex<<'t';
- return dest;
- }
- class Student:public Person{
- int id; //学号
- int Eng,Math,Phy; //三门课成绩
- double ave; //平均成绩
- ofstream ofile;
- public:
- Student(string n="noname",int i=0,char s='m',int e=0,int m=0,int p=0):Person(n,s){
- id=i; Eng=e; Math=m; Phy=p; CalAve();
- };
- ~Student();
- void CalAve(){ave=double(Eng+Math+Phy)/3;} ; //计算平均成绩
- friend ostream& operator<<(ostream& dest,Student& st);//输出姓名、性别、号、三门课成绩、平均成绩
- };
- Student::~Student(){
- ofile.open("myfile.txt");
- ofile<<"name"<<'t'<<"sex"<<'t'<<"id"<<'t';
- ofile<<"Eng"<<'t'<<"Math"<<'t'<<"Phy"<<'t'<<"ave"<<endl;
- ofile<<*this;
- ofile.close();
- }
- ostream& operator<<(ostream& dest,Student& st){
- Person *p=&st;
- dest<<*p; //利用赋值兼容原则输出st的基类成员
- dest<<st.id<<'t'<<st.Eng<<'t'<<st.Math<<'t'<<st.Phy<<'t'<<st.ave;
- return dest;
- }
- int main(){
- Student st("wang",22061,'m',90,80,85);
- cout<<"name"<<'t'<<"sex"<<'t'<<"id"<<'t';
- cout<<"Eng"<<'t'<<"Math"<<'t'<<"Phy"<<'t'<<"ave"<<endl;
- cout<<st<<endl;
- return 0;
- }