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

先编写程序:

#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;
}

运行结果:

The dogs 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函数中)访问。



更多内容请关注微信公众号
wchat.jpg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值