- 子类继承父类,父类里的成员可以被子类调用
#include <iostream.h> class Animal { public: void eat() { cout<<"animal eat"<<endl; } void sleep() { cout<<"animal sleep"<<endl; } }; class Fish:public Animal { }; void main() { Animal an; Fish fh; fh.sleep(); }
2.protected 成员被毕继承只能对在子类内部访问,不能直接访问,父类本身也不能访问。
#include <iostream.h> class Animal { public: void eat() { cout<<"animal eat"<<endl; } protected: void sleep() { cout<<"animal sleep"<<endl; } public: void breathe() { cout<<"animal breathe"<<endl; } }; class Fish:public Animal { public: void test() { sleep(); } }; void main() { Animal an; Fish fh; fh.test();//子类可以通过内部成员函数来访问父类的保护成员 fh.sleep();//子类不能直接访问父类的保护成员。 }
3. 继承中私有成员无论怎样都不能被子类访问!
4.构造函数。构造子类对象时,先执行父类的构造函数,再执行子类的构造函数。析构的顺序正好与其相反 。
#include <iostream.h> class Animal { public: Animal(){cout<<"Animal construction!"<<endl;} void eat() { cout<<"animal eat"<<endl; } protected: void sleep() { cout<<"animal sleep"<<endl; } public: void breathe() { cout<<"animal breathe"<<endl; } }; class Fish:public Animal { public: Fish(){cout<<"Fish construction!"<<endl;} void test() { sleep(); } }; void main() { // Animal an; Fish fh; fh.test();//子类可以通过内部成员函数来访问父类的保护成员 // fh.sleep();//子类不能直接访问父类的保护成员。 }
5.子类构造要先构造父类。当父类是有参构造函数,子类构造函数无参时,需要在后面加上 :父类的构造函数#include <iostream.h> class Animal { public: Animal(int height,int weigtht)//带参数的构造函数 {cout<<"Animal construction!"<<endl;} void eat() { cout<<"animal eat"<<endl; } protected: void sleep() { cout<<"animal sleep"<<endl; } public: void breathe() { cout<<"animal breathe"<<endl; } }; class Fish:public Animal { public: Fish():Animal(300,400) {cout<<"Fish construction!"<<endl;} void test() { sleep(); } }; void main() { // Animal an; Fish fh; fh.test();//子类可以通过内部成员函数来访问父类的保护成员 // fh.sleep();//子类不能直接访问父类的保护成员。 }
原文链接: https://www.cnblogs.com/zhangdongsheng/archive/2010/11/12/1875305.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/17289
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!