学习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)