虚继承(virtual inheritance) 详解

在多重继承(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 
#include 
     
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


来源:Mystra的CSDN博客

上一篇: 判断文件夹(folder)是否存在(exist)

下一篇: 通过私有(private)继承复用类实现工厂函数详解

分享到: 更多