继承
2016-04-04 14:29
323 查看
//继承 //1.不带参数 #include<iostream.h> 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 //animal 父类 fish 子类 //类中的protected在子类中可以访问,在外部不能 //类中的private在子类都不能被访问 //继承方式:public,private, { void test() { sleep(); breathe(); } }; int main() { animal an; an.eat(); fish fh; fh.sleep(); return 0; }
//2.带参数
include
using namespace std;class animal
{
public:
animal(int hight, int weight) //构造函数一般与类的名字相同
{
cout << “animal construct” << endl;
}
~animal()
{
cout << “animal deconstruct” << endl;
}
void eat()
{
cout << “animal eat” << endl;
}
void sleep()
{
cout << “animal sleep” << endl;
}
void breathe()
{
cout << “animal breathe” << endl;
}
};
//fish 继承animal后,其中的构造函数会不会被调用
//结果:fish 继承父类 ,可以调用父类的方法,因此先调用animal中的构造函数,在调用fish中的构造函数
//构造时,父类先,子类后
//析构时,子类先,父类后
class fish :public animal
{
public:
fish() : animal(400, 300),a(1)
//当父类中的构造函数带有参数时,
//当我们构造fish类的对象fh时,
//它需要先构造animal类的对象,
//调用animal类的默认构造函数(即不带参数的构造函数),
//而在我们的程序中,animal类只有一个带参数的构造函数,
//在编译时,因找不到animal类的默认构造函数而出错。
//解决方法:
//fish() : animal(400,300),向父类传递参数,还可以进行常量的初始化
{
cout << “fish construct” << endl;
}
~fish()
{
cout << “fish deconstruct” << endl;
}
private:
const int a;
};
int main()
{
// animal an;
// an.eat();
fish fh;
// fh.sleep();
return 0;
}
相关文章推荐
- Android Native 绘图方法
- PostgreSQL教程(三):表的继承和分区表详解
- C#中struct和class的区别详解
- Lua面向对象之类和继承浅析
- 浅析Ruby中继承和消息的相关知识
- VBS ArrayList Class vbs中的数组类
- 大家看了就明白了css样式中类class与标识id选择符的区别小结
- 设计引导--一个鸭子游戏引发的设计理念(多态,继承,抽象,接口,策略者模式)
- C++实现不能被继承的类实例分析
- C# 面向对象三大特性:封装、继承、多态
- PHP类的封装与继承详解
- 深入了解PHP类Class的概念
- js继承 Base类的源码解析
- jquery 表单验证之通过 class验证表单不为空
- Javascript 面向对象 继承
- JavaScript 继承使用分析
- Javascript面向对象编程(二) 构造函数的继承
- Javascript中的几种继承方式对比分析
- javascript面向对象之Javascript 继承
- JavaScript 对象、函数和继承