c++继承与派生
<1>.公有继承
#include <iostream> using namespace std; class vehicle { private: float weight; int wheels; public: vehicle(int in_wheels,float in_weight) { wheels=in_wheels; weight=in_weight; } int get_wheels() { return wheels; } float get_weight() { return weight; } }; class car:public vehicle { private: int passenger_load; public: car(int in_wheels,float in_weight,int people=5):vehicle(in_wheels,in_weight) { passenger_load=people; } int get_passenger() { return passenger_load; } }; int main() { car bm(4,100); cout<<bm.get_wheels()<<endl; cout<<bm.get_weight()<<endl; cout<<bm.get_passenger()<<endl; return 0; }
结果:
4
100
5
<2>.私有继承
#include <iostream> using namespace std; class vehicle { private: float weight; int wheels; public: vehicle(int in_wheels,float in_weight) { wheels=in_wheels; weight=in_weight; } int get_wheels() { return wheels; } float get_weight() { return weight; } }; class car:private vehicle { private: int passenger_load; public: car(int in_wheels,float in_weight,int people=5):vehicle(in_wheels,in_weight) { passenger_load=people; } int get_passenger() { return passenger_load; } int get_wheels() { return vehicle::get_wheels(); } int get_weight() { return vehicle::get_weight(); } }; int main() { car bm(4,100); cout<<bm.get_wheels()<<endl; cout<<bm.get_weight()<<endl; cout<<bm.get_passenger()<<endl; return 0; }
结果:
4
100
5
<3>.保护继承
#include <iostream> using namespace std; class vehicle { private: int wheels; protected: float weight; public: vehicle(int in_wheels,float in_weight) { wheels=in_wheels; weight=in_weight; } int get_wheels() { return wheels; } float get_weight() { return weight; } }; class car:protected vehicle { private: int passenger_load; public: car(int in_wheels,float in_weight,int people=5):vehicle(in_wheels,in_weight) { passenger_load=people; } int get_passenger() { return passenger_load; } int get_wheels() { return vehicle::get_wheels(); } int get_weight() { return weight; } }; int main() { car bm(4,100); cout<<bm.get_wheels()<<endl; cout<<bm.get_weight()<<endl; cout<<bm.get_passenger()<<endl; return 0; }
结果:
4
100
5
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。