/*
*Copyright (c) 2013, 烟台大学计算机学院
* All rights reserved.
* 作 者:申玉迪
* 完成日期:2014 年 5 月 13 日
* 版 本 号:v1.0
* 问题描述:长颈鹿类对动物类的继承
*/
#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;
}*/
//私有继承
/*class Giraffe: private Animal
{
public:
Giraffe() {}
void StrechNeck()
{
cout << "Strech neck \n";
}
void take()
{
eat(); //正确,私有继承下,基类的公有成员对派生类对象可见
drink(); // 错误,私有继承下,基类的私有成员派生类不可访问
play(); // 正确,私有继承下,基类的受保护成员对派生类可见
}
};
int main()
{
Giraffe gir;
gir.eat(); // 错误,私有继承下,基类中所有成员在派生类中全部为私有,类外不可访问
gir.play(); // _同上______________
gir.drink(); // __同上_____________
return 0;
}*/
//protected继承
class Giraffe: protected Animal
{
public:
Giraffe() {}
void StrechNeck()
{
cout << "Strech neck \n";
}
void take()
{
eat(); // 正确,protected继承下,基类的公有成员对派生类对象可见
drink(); // 错误,protected继承下,基类的私有成员派生类不可访问
play(); // 正确,protected继承下,基类的受保护成员对派生类可见
}
};
int main()
{
Giraffe gir;
gir.eat(); // 错误,protected继承下,基类中所有成员在派生类中全部为受保护的,类外不可访问
gir.play(); // _同上______________
gir.drink(); // __同上_____________
return 0;
}
十二周——长颈鹿对动物类的继承
最新推荐文章于 2024-12-30 02:30:00 发布