前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >小朋友学C++(8):继承

小朋友学C++(8):继承

作者头像
海天一树
发布2018-04-17 12:11:10
4790
发布2018-04-17 12:11:10
举报
文章被收录于专栏:海天一树海天一树

先编写程序:

代码语言:javascript
复制
#include <iostream>
using namespace std;
class Animal
{
protected:
    float weight;
public:
    void setWeight(float w) 
    {
        weight = w;
    }
    float getWeight()
    {
        return weight;
    }
    void breathe()
    {
        cout << "breathing..." << endl; 
    }   
};
class Dog : public Animal
{
private:
    int legs;
public:
    void setLegs(int number)
    {
        legs = number;  
    }
    int getLegs()
    {
        return legs;    
    }
    void bark()
    {
        cout << "wang! wang!" << endl;
    }   
};
int main(int argc, char** argv)
{
    Dog dog;
    dog.setWeight(12.5);
    dog.setLegs(4);
    cout << "The dog's weight is " << dog.getWeight() << "kg" << endl;
    cout << "The dog has " << dog.getLegs() << " legs" << endl; 
    dog.breathe();
    dog.bark();
    return 0;
}

运行结果:

代码语言:javascript
复制
The dog’s weight is 12.5kg
The dog has 4 legs
breathing...
wang! wang!

程序分析: (1)Animal为一个类,Dog为另一个类。 class Dog : public Animal 表示Dog类继承了 Animal类。此时,Animal就成了Dog的基类或父类。Dog就成了Animal的派生类或子类。

(2)体重和呼吸是所有动物的共性,所以weight和breathe()定义在类Animal中。腿和吠不是所有动物的共性,所以legs和bark()定义在了类Dog中。

(3)class Dog : public Animal , 这里的public表示继承方式 。 继承方式有三种:public, protected和private。 ① 父类为private的属性和方法,不能被子类继承。 ② 父类为protected的成员,若被子类public继承的,仍为子类的protected成员;若被子类protected或private继承的,变为子类的private成员。 ③ 父类为public的成员,若被子类public继承的,仍为子类的public成员;若被子类protected继承的,变为子类的protected成员;若被子类private继承的,变为子类的private成员。

注:这些不用强记,编多了自然就知道

(4)根据(3)中第③条的结论,若程序改为class Dog : protected Animal,则程序无法通过编译。因为setWeight()和getWeight()被protected继承后,变为Dog的protected成员,而protected成员,无法在类外部(比如main函数中)访问。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-12-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 海天一树 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档