课程首页在:http://blog.csdn.net/sxhelijian/article/details/11890759,内有完整教学方案及资源链接
【项目1 - 长颈鹿类对动物类的继承】理解基类中成员的访问限定符和派生类的继承方式
请在下面的程序中要求的位置写下注释,声明相应的语句在语法上是否正确,为什么。在第一个程序中给出了示例,其他位置请仿照完成。在上机时,可以编译程序加以验证,阅读错误给出的英文提示,并加以理解。
(1)public继承方式下
#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;
}
( 2 ) private 继承方式下
#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: 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;
}
( 3 ) protected 继承方式下
#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: protected 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;
}
=================== 迂者 贺利坚 CSDN博客专栏================= |== IT学子成长指导专栏 专栏文章的分类目录(不定期更新) ==| |== C++ 课堂在线专栏 贺利坚课程教学链接(分课程年级) ==| |== 我写的书——《逆袭大学——传给IT学子的正能量》 ==| ===== 为IT菜鸟起飞铺跑道,和学生一起享受快乐和激情的大学 ===== |