c++练习题---班级与班主任类(对象成员、初始化列表)

    技术2024-10-27  20

    6-2 班级与班主任类(对象成员、初始化列表) (20分)

    已有教师类的部分代码如下:

    class Teacher{ private: string name; //姓名 string course; //所教课程 public: Teacher(){}; Teacher(string name_,string course_); string getName(){return name;} string getCourse(){return course;} };

    请补充完整Teacher类的函数定义,并编写班级类Class的代码,使之得出样例的输出结果。 班级类中包含年级、班号以及班主任老师三个数据成员。

    裁判测试程序样例:

    class Teacher{ private: string name; //姓名 string course; //所教课程 public: Teacher(){}; Teacher(string name_,string course_); string getName(){return name;} string getCourse(){return course;} }; /* 请在这里填写答案 */ int main(){ Class c1(2,1,"ZhangXiaowen","math"); Class c2(3,2,"LiSisi"); Class c3(1,1); Class c4; return 0; }

    输入样例:

    本例没有输入。

    输出样例:

    在这里给出相应的输出。例如:

    grade:2 class no:1,head teacher:ZhangXiaowen(math) grade:3 class no:2,head teacher:LiSisi(chinese) grade:1 class no:1,head teacher:unknow(chinese) new class created.

    代码实现:

    第一种写法:

    #include<iostream> using namespace std; class Teacher{ private: string name; //姓名 string course; //所教课程 public: Teacher(){}; Teacher(string name_,string course_){ name=name_; course=course_; } string getName(){return name;} string getCourse(){return course;} }; class Class:public Teacher{ private: int grade; int clas; public: Teacher p; Class(int a,int b,string d="unknow",string e="chinese"):grade(a),clas(b),Teacher(d,e) { cout<<"grade:"<<grade<<"class no:"<<clas<<","<<"head teacher:"<<getName()<<"("<<getCourse()<<""<<")"<<endl; } Class() { cout<<"new class created."<<endl; } }; /* 请在这里填写答案 */ int main(){ Class c1(2,1,"ZhangXiaowen","math"); Class c2(3,2,"LiSisi"); Class c3(1,1); Class c4; return 0; }

     

    第二种写法:

    #include<iostream> using namespace std; class Teacher{ private: string name; //姓名 string course; //所教课程 public: Teacher(){}; Teacher(string name_,string course_){ name=name_; course=course_; } string getName(){return name;} string getCourse(){return course;} }; class Class{ private: int grade; int clas; public: Teacher p;//上面一个做法运用了继承,较为简单,这个运用到了,定义一个友元类 Class(int a,int b,string d="unknow",string e="chinese"):grade(a),clas(b),p(d,e)//对对象的初始化,下面是成员函数 { cout<<"grade:"<<grade<<"class no:"<<clas<<","<<"head teacher:"<<p.getName()<<"("<<p.getCourse()<<""<<")"<<endl; } Class() { cout<<"new class created."<<endl; } }; /* 请在这里填写答案 */ int main(){ Class c1(2,1,"ZhangXiaowen","math"); Class c2(3,2,"LiSisi"); Class c3(1,1); Class c4; return 0; }

     

    Processed: 0.012, SQL: 9