8.12 上机实践习题
1.定义一个学生类,包括数据成员为年龄、性别、身高、成绩及显示成员函数,最后声明一个该类的对象,调用相应的显示函数输出结果。
【提示】上述题目主要是要求读者熟悉类和对象的相关知识,重点是掌握类中各种成员的声明、定义和使用。
【关键代码】
01 class CStudent 02 { 03 public: 04 CStudent() 05 { 06 m_sex='m'; 07 m_age=18; 08 m_score=0; 09 m_height=150; 10 }; 11 CStudent(int age,int height,int score,char sex) 12 { 13 m_age=age; 14 m_height=height; 15 m_score=score; 16 m_sex=sex; 17 }; 18 void display() 19 { 20 cout<<"age height score sex"<<endl; 21 cout<<m_age<<""<<m_height<<""<<m_score<<""<<m_sex<<endl; 22 }; 23 private: 24 intm_age; 25 intm_height; 26 float m_score; 27 charm_sex; 28 };
2.定义一个包含复制构造函数的学生类,先定义一个该类对象,然后用该对象初始化另外一个对象,最后输出结果。
【提示】上述题目主要是要求读者掌握复制构造函数的相关知识,重点是掌握显式定义复制构造函数。
【关键代码】
01 class CStudent 02 { 03 public: 04 CStudent() 05 { 06 m_sex='m'; 07 m_age=18; 08 m_score=0; 09 m_height=150; 10 m_name=NULL; 11 }; 12 CStudent(int age,int height,int score,char*name,char sex) 13 { 14 m_age=age; 15 m_height=height; 16 m_score=score; 17 m_sex=sex; 18 m_name=new char(strlen(name)+1); 19 strcpy(m_name,name); 20 }; 21 22 CStudent(const CStudent&student) 23 { 24 m_age=student. m_age; 25 m_height=student. m_height; 26 m_score=student. m_score; 27 m_sex=student. m_sex; 28 m_name=new char(strlen(student. m_name)+1); 29 strcpy(m_name,student. m_name); 30 31 } 32 33 void display() 34 { 35 cout<<"name age height score sex"<<endl; 36 cout<<m_name<<m_age<<m_height<<m_score<<m_sex<<endl; 37 }; 38 private: 39 char*m_name; 40 intm_age; 41 intm_height; 42 floatm_score; 43 charm_sex; 44 };