类和对象 -----继承

22 篇文章 0 订阅
1:// lesson3.cpp : 定义控制台应用程序的入口点。


继承:基类(父类)派生类(子类)

以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    不管是哪一种继承,子类都包含了父类的所有的属性和方法

不同点在于子类对于父类的访问权限不同


class EatGrassAnimal : public Animal  //派生类
{
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不可访问


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值