首 页 | 新 闻 | Symbian | Android| Windows Mobile | J2ME | 下载中心 | 游戏策划招聘与求职 | 购书指南 | 视频教程
您现在的位置: 开发视界 >> Symbian >> 语言基础 >> 正文
C++中类的多态与虚函数的使用(2)
作者:管宁    文章来源:PConline    更新时间:2006-5-15 15:14:07
但是在实际工作中,很可能会碰到对象所属类不清的情况,下面我们来看一下派生类成员作为函数参数传递的例子,代码如下:

//例程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(); 
}

  例子中,对象a与b分辨是基类和派生类的对象,而函数test的形参却只是Vehicle类的引用,按照类继承的特点,系统把Car类对象看做是一个Vehicle类对象,因为Car类的覆盖范围包含Vehicle类,所以test函数的定义并没有错误,我们想利用test函数达到的目的是,传递不同类对象的引用,分别调用不同类的,重载了的,ShowMember成员函数,但是程序的运行结果却出乎人们的意料,系统分不清楚传递过来的基类对象还是派生类对象,无论是基类对象还是派生类对象调用的都是基类的ShowMember成员函数。

相关文章:
图文例解C++类的多重继承与虚拟继承(上)
C++类的分解,抽象类与纯虚函数的需要性
C++中类的多态与虚函数的使用(4)
C++中类的多态与虚函数的使用(3)
C++中类的多态与虚函数的使用(1)
C++面向对象编程入门:图例实解:C++中类的继承特性(3)
C++面向对象编程入门:图例实解:C++中类的继承特性(2)
C++面向对象编程入门:图例实解:C++中类的继承特性(1)
 

站点地图 | 加入收藏 | 联系站长 | 广告服务 |
QQ:280529124  Tel:0592-8271361 辽ICP备05021703号