在C ++中从基础调用潜在孩子的构造函数 [英] Calling constructor of potential child from base in C++
问题描述
如何实现这种模式:
class Base {//doesn't know anything about potential descendant-classes, like Child
public:
Base * foo( void) {
//some code
return ( Base *) new !Child-constructor!();
}
};
class Child : public Base { };
//—————————————————————————————————————————————————
#include <iostream>
#include <typeinfo>
using namespace std;
int main( void) {
Base * base_p = Child().f();
cout << typeid( *base_p).name(); //expected to get "Child"
return 0;
}
我找不到这种类型的结构的正确语法潜在子构造函数)。
I can't find the right syntax for this type of constructions (calling the "potential" child constructor).
UPD :我忘了提及(没有认为可以有误解) c $ c> Child 类在 Base
的定义中不可知。因此,我想要 foo
来调用要继承的类的构造函数。
UPD: I forgot to mention (didn't think that there can be missunderstanding), that Child
class must not be known in definition of Base
. So I wanted foo
to call the constructor of the class in which it's gonna be inherited.
推荐答案
...在Base的定义中不能知道Child类,所以我想要foo来调用类继承的类的构造函数。
"... that Child class must not be known in definition of Base. So I wanted foo to call the constructor of the class in which it's gonna be inherited."
IMHO最简单的方法是提供 模板工厂功能 c
IMHO the easiest way is to provide a templated factory function with Base
class Base {
public:
template<class Derived>
static std::unique_ptr<Base> foo( void) {
//some code
return std::unique_ptr<Base>(new Derived());
}
};
class Child : public Base {
public:
Child() {}
virtual ~Child() {}
};
int main() {
std::unique_ptr<Base> p = Base::foo<Child>();
return 0;
}
检查可编译的样本这里请。
这篇关于在C ++中从基础调用潜在孩子的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!