// Console03.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Animal
{
public:
void eat()
{
cout<<"animal eat"<<endl;
}
void sleep()
{
cout<<"animal sleep"<<endl;
}
void breathe()
{
cout<<"animal breathe"<<endl;
}
};
class Fish:public Animal
{
};
void main()
{
Animal an;
an.eat();
Fish fh;
fh.sleep();
int i;
cin>>i;
}
和C#一样它是用冒号来继承
Fish从Animal派生而来
所以fh也可以调用sleep方法
运行结果为:
animal eat
animal sleep
----------------------------------------------------------------------------------
// Console03.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Animal
{
public:
void eat()
{
cout<<"animal eat"<<endl;
}
protected:
void sleep()
{
cout<<"animal sleep"<<endl;
}
void breathe()
{
cout<<"animal breathe"<<endl;
}
};
class Fish:public Animal
{
public:
void test()
{
this->sleep(); //在子类里可以调用父类的protected方法
}
};
void main()
{
Animal an;
an.eat();
Fish fh;
// fh.sleep(); 这里的调用不成功,编译错误
fh.test();
int i;
cin>>i;
}
现在把sleep和breathe方法设置为protected的了
这样在子类里能访问它们 但是在main函数里就没有权限调用了
--------------------------------------------------------------------------------
// Console03.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Animal
{
public:
void eat()
{
cout<<"animal eat"<<endl;
}
protected:
void sleep()
{
cout<<"animal sleep"<<endl;
}
private:
void breathe()
{
cout<<"animal breathe"<<endl;
}
};
class Fish:public Animal
{
public:
void test()
{
this->sleep();
this->breathe();
}
};
void main()
{
Animal an;
an.eat();
Fish fh;
// fh.sleep();
fh.test();
int i;
cin>>i;
}
现在把breathe设置为private的了
所以在子类中也访问不了breathe
发生编译错误
分享到:
相关推荐
C++继承与多态性实验报告
在Qt中编写的c++继承的视频
C++继承与派生课件 很值得下载 C++继承与派生课件 很值得下载
08_31_C++ 继承的二义性08_31_C++ 继承的二义性08_31_C++ 继承的二义性08_31_C++ 继承的二义性08_31_C++ 继承的二义性08_31_C++ 继承的二义性08_31_C++ 继承的二义性08_31_C++ 继承的二义性08_31_C++ 继承的二义性08...
C++继承,虚函数与多态性专题.C++继承,虚函数与多态性专题.
c++继承中的三种访问权限 pdf,一个简单总结,方便查阅。
C++ 继承详解 C++ C++ 继承详解 C++ 继承详解 继承详解
C++中继承与派生的PPT课件 欢迎新手们参考
在Qt中编写的c++继承分类的视频
c++上的一道题,网上尚未有答案,来自郭文平老师的书
c++继承描述
信息科学技术学院《程序设计实习》,C++程序员入门级教程
入门基础实例 有关继承和派生的应用小程序 希望对大家有帮助
利用C++中的继承与多态,实验构造函数的作用
c++继承与派生习题答案
本资源是C++继承与派生类实验报告,欢迎大家下载阿!
c++继承与派生,上机操作题,帮助理解继承与派生
C++继承与多态C++继承与多态C++继承与多态C++继承与多态C++继承与多态C++继承与多态
很不错的C++课件,简单易懂,适合自学。深入浅出指点到位