下面的代码中的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