C++:虛繼承(virtual inheritance) 詳解

來源:互聯網
上載者:User

在多重繼承(multiple inheritance)中, 可能出現多個基類繼承自同一個基類, 即"菱形繼承", 會導致最頂層的基類, 被複製多次;

可以採用虛繼承(virtual inheritance)的方式, 使衍生類別(derived class)只保留最頂層基類的一個副本.

virtual, 即需要vptr(virtual table pointer), 即虛表指標, 額外佔用4個位元組;

代碼如下:

/*  * test.cpp  *  *  Created on: 2014.04.14  *      Author: Spike  */      /*eclipse cdt, gcc 4.8.1*/      #include <iostream>  #include <string>        using namespace std;        class File {private: int i[10];};        class InputFile : public File {};  class OutputFile : public File {};  class IOFile : public InputFile, public OutputFile {};        class vInputFile : virtual public File {};  class vOutputFile : virtual public File {};  class vIOFile :  public vInputFile, public vOutputFile {};        int main () {      std::cout << "File = " << sizeof(File) << std::endl;            std::cout << "InputFile = " << sizeof(InputFile) << std::endl;      std::cout << "OutputFile = " << sizeof(OutputFile) << std::endl;      std::cout << "IOFile = " << sizeof(IOFile) << std::endl;            std::cout << "virtual InputFile = " << sizeof(vInputFile) << std::endl;      std::cout << "virtual OutputFile = " << sizeof(vOutputFile) << std::endl;      std::cout << "virtual IOFile = " << sizeof(vIOFile) << std::endl;  }

輸出:

File = 40  InputFile = 40  OutputFile = 40  IOFile = 80  virtual InputFile = 44  virtual OutputFile = 44  virtual IOFile = 48

作者:csdn部落格 Spike_King

更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.