Mal*_*ous 2 c++ oop inheritance
下面代码中的Child构造函数调用其父构造函数来初始化自身.但是,除非Child也调用了祖父项构造函数,否则代码将无法编译,即使这是一个应该隐藏在Parent中的实现细节.我不想将此详细信息公开给Child类的用户,因为它可能在将来发生变化.如何让下面的代码工作?
我尝试将继承更改为'private',但是Child构造函数仍然需要知道这个私有安排,恕我直言有点挫败了私有继承的目的!
有什么建议?
#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;
}
Run Code Online (Sandbox Code Playgroud)
$ 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&)
| 归档时间: |
|
| 查看次数: |
1021 次 |
| 最近记录: |