定义一个Animal
类,成员包括:
(1)整数类型的私有数据成员m_nWeightBase
,表示Animal
的体重;
(2)整数类型的保护数据成员m_nAgeBase
,表示Animal的年龄;
(3)公有函数成员set_weight
,用指定形参初始化数据成员m_nWeightBase
;
(4)公有成员函数get_weight
,返回数据成员m_nWeightBase
的值;
(5)公有函数成员set_age
,用指定形参初始化数据成员m_nAgeBase
;
2、定义一个Cat
类,私有继承自Animal
类,其成员包括:
(1)string
类型的私有数据成员m_strName
;
(2)带参数的构造函数,用指定形参对私有数据成员进行初始化
;
(3)公有的成员函数set_print_age
,功能是首先调用基类的成员函数set_age
设置数据成员m_nAgeBase
的值为5,接着输出成员m_strName
的值,然后输出“, age = ”,最后输出基类的数据成员m_nAgeBase
的值。具体输出格式参见main函数和样例输出。
(4)公有的成员函数set_print_weight
,功能是首先调用基类的成员函数set_weight
设置数据成员nWeightBase
的值为6,接着输出成员m_strName
的值,然后输出“, weight = ”,最后调用基类的成员函数get_weight
输出基类的数据成员m_nAgeBase
的值。具体输出格式参见main函数和样例输出。
答案:
class Animal { private: int m_nWeightBase; protected: int m_nAgeBase; public: void set_weight(int weight) { m_nWeightBase = weight; } int get_weight() { return m_nWeightBase; } void set_age(int age) { m_nAgeBase = age; } }; class Cat : private Animal { private: string m_strName; public: Cat (string cat) { m_strName = cat; } void set_print_age() { set_age(5); cout << m_strName << ", age = " << m_nAgeBase << endl; } void set_print_weight() { set_weight(6); cout << m_strName << ", weight = " << get_weight() <<endl; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!