10.9 上机实践习题

    1.定义一个类point、然后将这个类作为基类,再定义一个类point3d让其继承于类point,然后定义类point3d的对象,最后调用显示输出的数据。

    【提示】上述题目主要是要求读者熟悉类继承的相关知识,重点是掌握类继承的概念及其作用。

    【关键代码】


    01 class point 02 { 03 public://public成员列表 04 int m_x; 05 int m_y; 06 07 point() 08 { 09 m_x=0; 10 m_y=0; 11 } 12 13 point(int x,int y) 14 { 15 m_x=x; 16 m_y=y; 17 } 18 19 void display() 20 { 21 cout<<"point x="<<m_x<<"point y="<<m_y<<endl; 22 } 23 }; 24 25 class point3d:public point 26 { 27 private: 28 int m_z; 29 public: 30 point3d():point() 31 { 32 m_z=0; 33 } 34 point3d(int x,int y,int z):point(x,y) 35 { 36 m_z=z; 37 } 38 void display() 39 { 40 cout<<"point3d x y z"<<m_x<<""<<m_y<<""<<m_z<<endl; 41 } 42 };

    2.用模拟代码来练习虚基派生的使用。

    【提示】上述题目主要是要求读者掌握虚基类的相关知识,重点是掌握虚基派生如何实现。

    【关键代码】


    01 class A//公共虚基类A 02 { 03 protected://protected成员列表 04 int x; 05 public: 06 A(int xp=0)//构造函数,带默认构造参数 07 { 08 x=xp; 09 } 10 void SetX(int xp)//SetX函数用以设置protected成员x 11 { 12 x=xp; 13 } 14 void print()//print函数输出信息 15 { 16 cout<<"this is x in A:"<<x<<endl; 17 } 18 }; 19 class B:virtual public A//类B由类A虚基派生而来 20 { 21 }; 22 class C:virtual public A//类C由类A虚基派生而来 23 { 24 }; 25 class D:public B,public C//类D由类B和类C共同派生 26 { 27 };