C++类的特性之继承

继承:

首先从一段代码开始:

#include <iostream>
using namespace std;

//动物
class animal{
public:
    void eat(){
        cout<<"eat"<<endl;
    }

    void sleep(){
        cout << "sleep" << endl;
    }

    void breath(){
        cout << "breat" << endl;

    }
};


//鱼
class fish{
public:
    void eat(){
        cout<<"eat"<<endl;
    }

    void sleep(){
        cout << "sleep" << endl;
    }

    void breath(){
        cout << "breat" << endl;

    }
};


//牛
class cot{
public:
    void eat(){
        cout<<"eat"<<endl;
    }

    void sleep(){
        cout << "sleep" << endl;
    }

    void breath(){
        cout << "breat" << endl;

    }
};

//如我我想要个鸡呢???再重写一遍代码吗????

如我我想要个鸡呢???再重写一遍代码吗????,我是个懒人,也是个聪明人,才不会一遍又一遍去做无聊的事情。

用继承,用继承的目的是为了重用代码,说白了就是想少写点代码。那让我们看看用继承如何实现功能?

#include <iostream>
using namespace std;

class animal{
public:
    void eat(){
        cout<<"eat"<<endl;
    }

    void sleep(){
        cout << "sleep" << endl;
    }

    void breath(){
        cout << "breat" << endl;

    }
};


class fish:public animal {

};

class duck:public animal{

};

int main() {

}

加餐:

#include <iostream>
using namespace std;

class animal{
public:

    animal(){
        cout<<"我是动物"<<endl;
    }
    void eat(){
        cout<<"eat"<<endl;
    }

    void sleep(){
        cout << "sleep" << endl;
    }

    void breath(){
        cout << "breat" << endl;

    }
};


class fish:public animal {
public:
    fish(){
        cout << "我是鱼" << endl;
    }
};

int main() {
    fish fi;
}

请问控制台会输出什么?animal和fish构造函数的调用顺序是什么??
这里写图片描述
解释:没有父亲就没有孩子,因为fish是从annimal继承过来的,所以在fish类的对象构造之前,annimal对象要先构造。再多说一点,构造函数和析构函数调用顺序刚好相反。

子类调用父类的构造函数

C++调用父类的构造函数就是在子类构造函数后加上:父类构造函数,这样子类构造函数被调用时,系统就会去调用父类的呆参构造函数。

#include <iostream>
using namespace std;

class animal{

private:
    int height;
    int weight;

public:
    animal(int height,int weight){
        this->height = height;
        this->weight = weight;

        cout<<"我是动物"<<endl;
    }
    void eat(){
        cout<<"eat"<<endl;
    }

    void sleep(){
        cout << "sleep" << endl;
    }

    void breath(){
        cout << "breat" << endl;
    }
    void output(){
        cout << weight << endl << height << endl;
    };
};

class fish:public animal {
public:
    fish():animal(500,600){
        cout << "我是鱼" << endl;
    }
};

int main() {
    fish fi;
    fi.output();
}

这里写图片描述


多重继承,我不习惯用,所以不到万不得已不用多重继承。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值