但是它的确是支持类,支持类并不能说明就是支持面向对象,能够解决多态问题的语言,才是真正支持面向对象的开发的语言,所以务必提醒有过其它非面向对象语言基础的读者注意!
多态的这个概念稍微有点模糊,如果想在一开始就想用清晰用语言描述它,让读者能够明白,似乎不太现实,所以我们先看如下代码:
//程序作者:管宁 //站点:www.cndev-lab.com //所有稿件均有版权,如要转载,请务必著名出处和作者 //例程1 #include <iostream> using namespace std; class Vehicle { public: Vehicle(float speed,int total) { Vehicle::speed=speed; Vehicle::total=total; } void ShowMember() { cout<<speed<<""<<total<<endl; } protected: float speed; int total; }; class Car:public Vehicle { public: Car(int aird,float speed,int total):Vehicle(speed,total) { Car::aird=aird; } void ShowMember() { cout<<speed<<""<<total<<""<<aird<<endl; } protected: int aird; }; void main() { Vehicle a(120,4); a.ShowMember(); Car b(180,110,4); b.ShowMember(); cin.get(); } |
但是在实际工作中,很可能会碰到对象所属类不清的情况,下面我们来看一下派生类成员作为函数参数传递的例子,代码如下:
//程序作者:管宁 //站点:www.cndev-lab.com //所有稿件均有版权,如要转载,请务必著名出处和作者 //例程2 #include <iostream> using namespace std; class Vehicle { public: Vehicle(float speed,int total) { Vehicle::speed=speed; Vehicle::total=total; } void ShowMember() { cout<<speed<<""<<total<<endl; } protected: float speed; int total; }; class Car:public Vehicle { public: Car(int aird,float speed,int total):Vehicle(speed,total) { Car::aird=aird; } void ShowMember() { cout<<speed<<""<<total<<""<<aird<<endl; } protected: int aird; }; void test(Vehicle &temp) { temp.ShowMember(); } void main() { Vehicle a(120,4); Car b(180,110,4); test(a); test(b); cin.get(); } |