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