Pages

2010年12月31日 星期五

C++多重繼承

下面為C++多重繼承的網路經典範例。

//程序作者:管寧
//站點:www.cndev-lab.com
//所有稿件均有版權,如要轉載,請務必著名出處和作者

#include <iostream>
using namespace std;

class Vehicle {
public:
    Vehicle(int weight = 0) {
        Vehicle::weight = weight;
        cout << "載入Vehicle類構造函數" << endl;
    }
    void SetWeight(int weight) {
        cout << "重新設置重量" << endl;
 Vehicle::weight = weight;
    }
    virtual void ShowMe() = 0;
protected:
    int weight;
};

class Car: virtual public Vehicle//汽車,這裡是虛擬繼承
{
public:
    Car(int weight = 0, int aird = 0) : Vehicle(weight) {
        Car::aird = aird;
        cout << "載入Car類構造函數" << endl;
    }
    void ShowMe() {
        cout << "我是汽車!" << endl;
    }
protected:
    int aird;
};

class Boat: virtual public Vehicle//船,這裡是虛擬繼承
{
public:
    Boat(int weight = 0, float tonnage = 0) : Vehicle(weight) {
        Boat::tonnage = tonnage;
        cout << "載入Boat類構造函數" << endl;
    }
    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)
    //多重繼承要注意調用基類構造函數
    {
        cout << "載入AmphibianCar類構造函數" << endl;
    }
    void ShowMe() {
        cout << "我是水陸兩用汽車!" << endl;
    }
    void ShowMembers() {
     cout << " 重量:" << weight << "頓," << "空氣排量:" << aird << "CC," << "排水量:" << tonnage << " 頓" << endl;
    }
};
int main() {
    AmphibianCar a(4, 200, 1.35f);
    a.ShowMe();
    a.ShowMembers();
    a.SetWeight(3);
    a.ShowMembers();
    system("pause");
    return 0;
}


載入Vehicle類構造函數
載入Car類構造函數
載入Boat類構造函數
載入AmphibianCar類構造函數
我是水陸兩用汽車!
 重量:4頓,空氣排量:200CC,排水量:1.35 頓
重新設置重量
 重量:3頓,空氣排量:200CC,排水量:1.35 頓
請按任意鍵繼續 . . . 
但是C++多重繼承有個問題是當繼承的方法或變數有相同的時候,到底要用哪種呢?

是否有方法可以直接指定要用哪個繼承的方法?

#include <iostream>
using namespace std;
class AA {
public:
    AA() {
    }
    void fat() {      
 printf("Addidas is Fat\n");
    }
};

class BB {
public:
    BB() {
    }
    void fat() {
 printf("Bill is Fat\n");
    }
};



class CC: public AA, public BB {
public:
    using AA::fat;
    CC() {

    }
};

class DD: public AA, public BB {
public:
    DD() {
    }
};

int main() {
    CC ca;
    printf("C is call..: ");
    ca.fat();
    DD da;
    printf("D is call..: \n");
    da.AA::fat();
    da.BB::fat();
    return 0;
}


C is call..: Addidas is Fat
D is call..: 
Addidas is Fat
Bill is Fat

由此可知,AA::fat() using AA::fat 皆可指定繼承的哪個方法會被使用。

0 意見: