继承
//动物、鱼、狗都有吃、睡、跑的特性 //当没有使用继承时需要分别定义各自的类,重复并且麻烦 //未使用继承时 #include <iostream.h> class Animal { public: void eat() { cout<<"animal eat"<<endl; } void sleep() { cout<<"animal sleep"<<endl; } void run() { cout<<"animal run"<<endl; } }; class Fish { void eat() { } void sleep() { } void run() { } }; class Dog { void eat() { } void sleep() { } void run() { } }; //使用继承时 #include <iostream.h> class Animal { public: //基类权限******************************************* //public所有地方都可以访问 //private外部和子类中都不能访问 //protected外部不能访问只能在子类中访问 void eat() { cout<<"animal eat"<<endl; } void sleep() { cout<<"animal sleep"<<endl; } void run() { cout<<"animal run"<<endl; } }; class Fish : public Animal //继承的语法:在类的名字后加入“: public 父类名” { }; //Animal叫做基类(父类),Fish就是Animal的派生类(子类) //此处的派生类继承特性为上行中的public //派生类继承特性的权限************************************ /* 基类的访问特性 类的继承特性 派生类的访问特性 public public public protected protected private no access public protected protected protected protected private no access public private private protected private private no access */ void main() { Animal an; an.eat(); Fish fh; fh.sleep(); } //程序运行结果 /* animal eat animal sleep Press any key to continue 由此可见,Fish已经继承了Animal */
posted on 2015-06-09 00:29 Rohalloway 阅读(114) 评论(0) 编辑 收藏 举报