继承:基类(父类)派生类(子类)
以animal(动物)eatgrassanimal(食草动物)rabbit(兔子)举例
#include "stdafx.h"#include <iostream>
using namespace std;
class Animal //基类
{
public:
Animal(){ cout << "animal的默认构造函数" << endl; }
Animal(int age){ m_age = age; cout << "animal的定义构造函数"<< endl; }
int getAge(){ return m_age; }
void run(){ cout << "animal run" << endl; }
private:
int m_age;
protected:
};
//继承的3中方法,public protected private 不管是哪一种继承,子类都包含了父类的所有的属性和方法
不同点在于子类对于父类的访问权限不同
{
public:
EatGrassAnimal(int age);
void eat(){ cout << "I am eat grass" << endl; }
int getAge(){ return m_age; }
private:
int m_age;
protected:
};
EatGrassAnimal::EatGrassAnimal(int age) :Animal(age) //构造函数初始化时 先执行初始化列表在执行函数体内部
{
m_age = 20; 派生类中初始化父类的数据成员,当然子类也可以继续添加,初始化自己的数据成员
}
class Rabbit : public EatGrassAnimal
{
public:
Rabbit(int age);
int getAge(){ return m_age; }
private:
int m_age;
protected:
};
Rabbit::Rabbit(int age) :EatGrassAnimal(age) 这个地方子类只能调用自己的父类的构造函数,不能越级调用animal类
{
m_age = 30;
}
int _tmain(int argc, _TCHAR* argv[])
{
Rabbit rabbit(2); rabbit类定义了一个对象,构造函数调用的顺序,先调用animal类,在调用eatgrassanimal 后调用rabbit类,析构函数调用的顺序与构造函数 相反
rabbit.run();rabbit.eat();
cout << rabbit.getAge() << endl; 3个类中同时有getage成员函数时,就近原则
cout << rabbit.Animal::getAge() << endl; 若想调用具体的某一个类中的成员函数时,前面加类名和类限定符
cout << rabbit.EatGrassAnimal::getAge() << endl;cout << rabbit.Rabbit::getAge() << endl;
system("pause");
return 0;
}
3中继承方式的区别:
如果不申明某种继承方式时,默认private继承
public: 父类中的public---->子类中的public protected->protected private 不可访问
protected public ->protected protected->protected private不可访问
父类的public变成子类的protected,外部无法访问
private public-> private protected->protected private不可访问