20.6 上机实践习题
1.下面给出一段代码,请读者自己进行编译,判断是否有问题,如果有问题,请找出问题并修改,直到编译通过。
【提示】上述题目主要是要求读者熟悉编译过程的相关知识,重点是掌握编译中的排错和修订。
【关键代码】
01 #include<iostream> 02 using namespace std; 03 04 class base 05 { 06 public: 07 virtual void disp() 08 { 09 cout<<"hello,base"<<endl; 10 } 11 }; 12 class child1:public base 13 { 14 public: 15 void disp() 16 { 17 cout<<"hello,child1"<<endl; 18 } 19 }; 20 21 class child2:public base 22 { 23 public: 24 void disp() 25 { 26 cout<<"hello,child2"<<endl; 27 } 28 }; 29 30 int main() 31 { 32 base obj_base; 33 child1 obj_child1; 34 child2 obj_child2; 35 disp(&obj_base); 36 disp(&obj_child1); 37 disp(&obj_child2); 38 return 0; 39 40 } 41 42 void disp(base*p) 43 { 44 p->disp(); 45 }
2.下面给出一段代码,请读者自己进行编译,判断是否有问题,如果有问题,请找出问题并修改,直到编译通过。
【提示】上述题目主要是要求读者熟悉编译过程的相关知识,重点是掌握编译中的排错和修订。
【关键代码】
01 #include<iostream> 02 using namespace std; 03 class CStudent 04 { 05 public: 06 CStudent() 07 { 08 m_name=NULL; 09 m_age=18; 10 m_score=0; 11 m_height=150; 12 }; 13 CStudent(char*name,int age,int height,int score) 14 { 15 m_age=age; 16 m_height=height; 17 m_score=score; 18 m_name=new char[strlen(name)+1]; 19 strcpy(m_name,name); 20 }; 21 ~CStudent() 22 { 23 if(m_name!=NULL) 24 delete[]m_name; 25 m_name=NULL; 26 } 27 void display(CStudent&stud); 28 private: 29 intm_age; 30 intm_height; 31 float m_score; 32 char*m_name; 33 }; 34 35 void display(CStudent&stud) 36 { 37 cout<<"name age height score"<<endl; 38 cout<<stud. m_name<<""<<stud.m_age<<""<<stud.m_height<<"" 39 <<stud. m_score<<""<<endl; 40 } 41 42 int main() 43 { 44 CStudent std1("wanghao",20,176,90); 45 CStudent std2("liangliping",18,158,80); 46 display(std1); 47 display(std2); 48 return 0; 49 }