12.1

#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;
}

你可能感兴趣的:(C++,类,对象)