C++

派生类练习

#include <iostream>
#include <string>
using namespace std;

class Animal
{
public:
Animal()
{}
void set_weight(int w)
{
m_nWeightBase=w;
}
int get_weight()
{
return m_nWeightBase;
}
void set_age(int y)
{
m_nAgeBase=y;
}
private:
int m_nWeightBase;
protected:
int m_nAgeBase;
};
class Cat:private Animal
{
private:
string m_strName;
public:
Cat(string n)
{
m_strName=n;
}
void set_print_age()
{
set_age(5);
cout<<m_strName<<", age = "<<Animal::m_nAgeBase<<endl;
}
void set_print_weight()
{
set_weight(6);
cout<<m_strName<<", weight = "<<Animal::get_weight()<<endl;
}
};

int main()
{
Cat cat("Persian"); //定义派生类对象cat
cat.set_print_age();
cat.set_print_weight(); //派生类对象调用自己的公有函数
return 0;
}

posted @   涨涨涨张  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示