c++练习题-----6-2派生类使用基类的成员函数

    技术2022-07-14  90

    6-2派生类使用基类的成员函数(15分) 按要求完成下面的程序: 1、定义一个Animal类,成员包括: . (1)整数类型的私有数据成员m_ nWeightBase], 示Animal的体重; (2)整数类型的保护数据成员m nAgeBase ,示Animal的年龄; (3)公有函数成员set. weight),用指定形参初始化数据成员nWeightBase | ; (4)公有成员函数get_ weight, 返回数据成员nweightBase的值; (5)公有函数成员set_ age], 用指定形参初始化数据成员m nAgeBase ; 2、定义一个Cat类,公有继承自Animal类,其成员包括: . (1) string类型的私有数据成员m strName ; (2)带参数的构造函数,用指定形参对私有数据成员进行初始化; (3)

    具体输出格式参见main函数和样例输出。 参见题目描述。 裁判测试程序样例: #include <iostream> #include <string> using namespace std; /* 请在这里填写答案 */ int main( ) Cat cat("Persian"); //定 义派生类对象cat cat.set_ age(5); //派生类对象调用从基类继承的公有成员函数 cat.set_ _weight(6); //派生类对象 调用从基类继承的公有成员函数 cat.print_ age(); //派生类对象调用自己的公有函数 cout << "cat weight =”<< cat.get_ weight() << endl; return 0 输入样例: 本题无输入。 输出样例: . Persian,age = 5 cat weight = 6  

    代码实现:

    #include<iostream> #include<cstring> using namespace std; class Animal{ private: int m_nWeightBase;//体重 protected: int m_nAgeBase;// 年龄 public: void set_weight(int a){ m_nWeightBase=a; } void set_age(int b) { m_nAgeBase=b; } int get_weight(){ return m_nWeightBase; } }; class Cat:public Animal { private: string m_strName; public: void print_age() { cout<<m_strName<<", age ="<<m_nAgeBase<<endl; } Cat(string a) {m_strName=a; } }; int main() { Cat cat("Persian"); //定 义派生类对象 cat.set_age(5);//派生类对象调用从基类继承的公有成员函数 cat.set_weight(6); //派生类对象 调用从基类继承的公有成员函数 cat.print_age();//派生类对象调用自己的公有函数 cout << "cat weight ="<< cat.get_weight() << endl; return 0; }

     

     

     

     

     

     

    Processed: 0.008, SQL: 9