程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> C++:虛繼承(virtual inheritance) 詳解

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

編輯:關於C++

在多重繼承(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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved