学习C++(九)

继承

继承:代码复用
  派生类会继承基类的所有(非静态)属性和行为
  派生类虽然拥有基类的属性和行为, 但是派生类中不能直接初始化基类的属性
  必须调用基类的构造函数来初始化基类的部分.
  当一个派生类要使用构造函数初始化基类的成员时,我们只需要关心它的直接基类既可.
  QPushButton ( const QIcon & icon,
    const QString & text, QWidget * parent = 0 );

  class MyButton : public QPushButton{
    public:
      MyButton(int clickedCount, const QIcon& icon,
        const QString& text, QWidget* parent = 0)
        :QPushButton(icon, text, parent),
    clickedCount(clickedCount)
    {
    }
    private:
      int clickedCount;
  };

#include <iostream>
using namespace std;

//基类/父类
class Animal{
   //动物类
private:
	int 		animal_year;			//生命
public:
	Animal(int animal_year)
		:animal_year(animal_year)
	{
   
	
	}
	void eat() const {
    cout << "Animal::eat" << endl; }
};

//is - a
//派生类/子类
class Bird : public Animal{
   //鸟类继承动物类
private:
	int 		wing;					//翅膀
public:
	Bird(int animal_year, int wing)
		:Animal(animal_year),			//调用基类的构造函数
		wing(wing)
	{
   
	
	}
	void fly() const {
    cout << "Bird::fly" << endl; }
};

class Parrot : public Bird{
   //鹦鹉类继承鸟类
private:
	string	color;
public:
	Parrot(int animal_year, int wing, const string& color)
		:Bird(animal_year, wing),
		color(color)
	{
   
	
	}
	void speak() const {
    cout << "Parrot::speak" << endl; }
};


int main(void)
{
   
	Animal animal(10);
	animal.eat();

    cout << "******" <<endl;
	Bird b(4, 2)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值