/*
*Corpyright (c)2013,烟台大学计算机学院
*All right reseved.
*作者:张梦佳
*完成日期:2014年5月13日
*版本号:v1.0
*输入描述:
*问题描述:找错!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(); // 错误,drink是私有函数,无法访问!
play(); // 正确,公有继承下,基类的保护成员对派生类可见
}
};
int main()
{
Giraffe gir; //定义派生类的对象
gir.eat(); // 正确,公有继承下,基类的公有成员对派生类对象可见
//gir.play(); // 错误,play是保护函数,无法访问!
//gir.drink(); // 错误,drink是私有函数,无法访问!
//gir.take(); // 错误,take是私有函数,无法访问!
gir.StrechNeck(); // 正确,
Animal ani;
ani.eat(); // 正确
//ani.play(); //错误
//ani.drink(); // 错误
//ani.take(); //错误,派生类的成员对基类对象(不论访问属性)不可见
//ani.StrechNeck(); //错误
return 0;
}
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;
}
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;
}