2010-12-19 94 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

当虚拟继承被移除时,它对我很好。

相关问题