C++:虚担任(virtual inheritance) 详解
当前位置:以往代写 > C/C++ 教程 >C++:虚担任(virtual inheritance) 详解
2019-06-13

C++:虚担任(virtual inheritance) 详解

C++:虚担任(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 <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

    关键字:

在线提交作业