首 页 | 新 闻 | Symbian | Android| Windows Mobile | J2ME | 下载中心 | 游戏策划招聘与求职 | 购书指南 | 视频教程
您现在的位置: 开发视界 >> Symbian >> 语言基础 >> 正文
图文例解C++类的多重继承与虚拟继承(上)
作者:管宁    文章来源:PConline    更新时间:2006-5-19 14:05:46
在过去的学习中,我们始终接触的单个类的继承,但是在现实生活中,一些新事物往往会拥有两个或者两个以上事物的属性,为了解决这个问题,C++引入了多重继承的概念,C++允许为一个派生类指定多个基类,这样的继承结构被称做多重继承

  举个例子,交通工具类可以派生出汽车和船连个子类,但拥有汽车和船共同特性水陆两用汽车就必须继承来自汽车类与船类的共同属性。

  当一个派生类要使用多重继承的时候,必须在派生类名和冒号之后列出所有基类的类名,并用逗好分隔。

//程序作者:管宁   
//站点:www.cndev-lab.com   
//所有稿件均有版权,如要转载,请务必著名出处和作者   
 
#include <iostream
using namespace std; 
 
class Vehicle 

    public
        Vehicle(int weight = 0) 
        { 
            Vehicle::weight = weight; 
        } 
        void SetWeight(int weight) 
        { 
            cout<<"重新设置重量"<<endl; 
            Vehicle::weight = weight; 
        } 
        virtual void ShowMe() = 0; 
    protected
        int weight; 
}; 
class Car:public Vehicle//汽车 

    public
        Car(int weight=0,int aird=0):Vehicle(weight) 
        { 
            Car::aird = aird; 
        } 
        void ShowMe() 
        { 
            cout<<"我是汽车!"<<endl; 
        } 
    protected
        int aird; 
}; 
 
class Boat:public Vehicle//船 

    public
        Boat(int weight=0,float tonnage=0):Vehicle(weight) 
        { 
            Boat::tonnage = tonnage; 
        } 
        void ShowMe() 
        { 
            cout<<"我是船!"<<endl; 
        } 
    protected
        float tonnage; 
}; 
 
class AmphibianCar:public Car,public Boat//水陆两用汽车,多重继承的体现 

    public
        AmphibianCar(int weight,int aird,float tonnage) 
        :Vehicle(weight),Car(weight,aird),Boat(weight,tonnage) 
        //多重继承要注意调用基类构造函数 
        { 
         
        } 
        void ShowMe() 
        { 
            cout<<"我是水陆两用汽车!"<<endl; 
        } 
}; 
int main() 

    AmphibianCar a(4,200,1.35f);//错误 
    a.SetWeight(3);//错误 
    system("pause");  
}

  上面的代码从表面看,看不出有明显的语发错误,但是它是不能够通过编译的。这有是为什么呢?
  这是由于多重继承带来的继承的模糊性带来的问题。

相关文章:
在没有ui的程序中捕获所有的key事件
Symbian类里的extension和reserved
Symbian应用程序中如何备份和载入
播放WAV文件
Symbian程序中的观察者模式
S60平台:Bluetooth API开发伙伴指南——搜索和发布
如何在SYMBIAN60中编写DLL
C++ 基类和派生类
 

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