下面的代碼中的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&)
[gcc C++虛擬繼承問題]的可能重複(http://stackoverflow.com/questions/2126522/gcc-c-virtual-inheritance-problem) – 2010-12-19 10:58:55