首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 虛擬繼承:解決菱形繼承重複基類別問題

     編輯:關於C++

菱形繼承問題

多重繼承中,若兩個基類別共同繼承自同一個基類別,最底層派生類別會包含兩份頂層基類別子物件,導致資料重複與存取模糊。

虛擬繼承解決方案

在中間層基類別繼承頂層基類別時加上 virtual 關鍵字(virtual public Base),確保最底層派生類別只保留一份頂層基類別子物件。

程式碼示範

/* cppprimer.cpp
 * Created on: 2014.1.10
 * Author: Spike
 */
#include <iostream>
#include <string>

class ZooAnimal {
public:
    void zooprint() { cout << "Zoo Animal!" << endl; }
};
class Raccoon : public virtual ZooAnimal {
public:
    void raccprint() { cout << "Raccoon!" << endl; }
};
class Bear : public virtual ZooAnimal {
public:
    void bearprint() { cout << "Bear!" << endl; }
};
class Panda : public Bear, public Raccoon {
public:
    void pandprint() { cout << "Panda!" << endl; }
};

void dance(Bear& B) { B.bearprint(); }
void rummage(Raccoon& R) { R.raccprint(); }

int main() {
    Panda P;
    P.zooprint(); // 呼叫唯一的 ZooAnimal::zooprint
    dance(P);
    rummage(P);
}

輸出結果

Zoo Animal!
Bear!
Raccoon!

記憶體配置差異

  • 非虛擬繼承:sizeof(IOFile) == 2 * sizeof(File)(兩份基類別)。
  • 虛擬繼承:sizeof(vIOFile) == sizeof(File) + 2 * sizeof(vptr)(一份基類別 + 虛擬基類別指標)。

注意事項

  • 虛擬基類別由最底層派生類別直接建構,建構順序優先於非虛擬基類別。
  • 虛擬繼承引入額外間接層(虛擬基類別表),存取虛擬基類別成員稍慢。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved