长颈鹿类对动物类的public继承

来源:互联网 发布:sql中prompt 编辑:程序博客网 时间:2024/05/16 01:14
#include <iostream>using namespace std;class Animal    //动物类{public:    Animal() {}    void eat(){        cout << "eat\n";    }protected:    void play()    {        cout << "play\n";    }private:    void drink()    {        cout << "drink\n";    }};class Giraffe: public Animal   //长颈鹿类{public:    Giraffe() {}    void StrechNeck()    {        cout << "Strech neck \n";    }private:    void take()    {        eat();        //正确,公有继承下,基类的公有成员对派生类可见        //drink();    //错误,基类的私有成员,不可访问        play();       //正确,派生类的成员函数可以访问当前对象的基类的保护成员    }};int main(){    Giraffe gir;      //定义派生类的对象    gir.eat();          //正确,公有继承下,基类的公有成员对派生类对象可见    //gir.play();       //错误,基类的保护成员,派生类不可访问    //gir.drink();      //错误,基类的私有成员,派生类不可访问    //gir.take();       //错误,派生类的私有成员,类外不可访问    gir.StrechNeck();   //正确,派生类的公有成员,类外可访问    Animal ani;    ani.eat();          //正确,基类公有成员,类外可访问    //ani.play();       //错误,基类的保护成员,类外不可访问    //ani.drink();      //错误,基类的私有成员,类外不可访问    //ani.take();       //错误,派生类的成员对基类对象(不论访问属性)不可见    //ani.StrechNeck(); //错误,派生类的成员对基类对象(不论访问属性)不可见    return 0;} 


总结:基类的private成员,可以被以下函数访问:基类的成员函数和基类的友元函数;

           基类的protected成员,可以被以下函数访问:基类的成员函数和基类的友元函数,派生类的成员函数可以访问当前对象的基类的保护成员。

0 0
原创粉丝点击