您的位置:首页 > 编程语言 > C语言/C++

C++程序设计课后习题及解答(第七章)

2016-01-03 19:06 375 查看
(1).如果派生类B已经重载了基类A的一个成员函数fn1(),没有重载基类A的成员函数fn2(),如何在派生类的函数中调用基类的成员函数fn1(),fn2()?



答:重载了基类的成员函数在派生类中的调用方法A::fn1();未重载基类的成员函数在派生类中的调用方法fn2();



(2).定义一个object类,有数据成员weight及函数成员:构造函数、析构函数、SetWeight()、Getweight(),由其公有派生类box类,增加数据成员height和width及函数成员:构造函数、析构函数、GetWidth()、SetWidth()、GetHeight()、setHeight()。声明一个box对象,观察构造函数和析构函数的调用顺序,并测试类中的操作函数是否正确运行。



答:

<span style="font-size:14px;">#include<iostream>
using namespace std;
 
class Object
{
         public:
                   voidSet_Weight(int W) {Weight=W;}
                   intGet_Weight( ) {return Weight;}
                   Object(){}
                   ~Object(){}
 
         private:
                   intWeight;
};
 
class Box:public Object
{
         public:
                   voidSet_width(int w){width=w;}
                   intGet_width(){return width;}
 
                   voidSet_height(int h){height=h;}
                   intGet_height(){return height;}
 
                   Box(inth=0,int w=0){height=h;width=w;}
                   ~Box(){}
 
         private:
                   intheight,width;
};
 
int main()
{
         Box mybox1;
         Box mybox2;
 
         mybox2.Set_height(10);
         mybox2.Set_width(20);
 
         cout<<mybox2.Get_height()<<endl;
         cout<<mybox2.Get_width()<<endl;
        
 
         cout<<mybox1.Get_height()<<endl;
         cout<<mybox1.Get_width()<<endl;
        
         return 0;
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: