2010-12-19 95 views
2

下面的代碼中的Child構造函數調用它的父構造函數來初始化它自己。但是,除非Child也調用祖父構造函數,否則代碼將不會編譯,儘管這是一個應該隱藏在Parent中的實現細節。我不想將這些細節公開給Child類的用戶,因爲它將來可能會改變。我如何獲得下面的代碼工作?如何避免在C++中調用祖父構造函數?

我試着改變繼承爲'私人',但子構造函數仍然期望知道這個私人安排,恕我直言有點挫敗私人繼承的目的!

有什麼建議嗎?

#include <iostream> 

class MyObject { 
    public: 
    MyObject(int i) { 
     std::cout << "MyObject(" << i << ") constructor" << std::endl; 
    } 
}; 

class Grandparent { 
    public: 
    Grandparent(MyObject i) 
    { 
    }; 
}; 

class Parent: virtual public Grandparent { 
    public: 
    Parent(int j) : 
     Grandparent(MyObject(j)) 
    { 
    }; 
}; 

class Child: virtual public Parent { 
    public: 
    Child() : 
     //Grandparent(MyObject(123)), // Won't work without this 
     Parent(5) 
    { 
    }; 
}; 

int main(void) 
{ 
    Child c; 
    return 0; 
} 
$ g++ -o test test.cpp 
test.cpp: In constructor ‘Child::Child()’: 
test.cpp:29: error: no matching function for call to ‘Grandparent::Grandparent()’ 
test.cpp:12: note: candidates are: Grandparent::Grandparent(MyObject) 
test.cpp:10: note:     Grandparent::Grandparent(const Grandparent&) 
+0

[gcc C++虛擬繼承問題]的可能重複(http://stackoverflow.com/questions/2126522/gcc-c-virtual-inheritance-problem) – 2010-12-19 10:58:55

回答

5

這是因爲繼承是虛擬的。虛擬繼承不能成爲實現細節,因爲Child類必須管理任何乘法繼承類的實例。如果你使用正常的繼承,那麼這應該不成問題。

+0

這似乎是問題 - 謝謝!任何指針/推理爲什麼這是這種情況? – Malvineous 2010-12-19 10:53:57

+0

@Malvineous,[本文](http://www.learncpp.com/cpp-tutorial/118-virtual-base-classes/)是我設法找到的最好的解釋。基本上,它要確保即使在多重繼承的情況下,虛擬基構造函數也只會被調用一次(通過大多數派生類,超出正常的構造函數鏈)。 – 2010-12-19 11:15:50

+0

@Sergey:現在我明白爲什麼它是這樣 - 非常感謝! – Malvineous 2010-12-20 03:17:06

1

當虛擬繼承被移除時,它對我很好。

相關問題