说我有一个类:
class Foo{
public:
Foo(){
}
//Is it possible to create a function like this:
virtual Foo* createOb(){
//Should create a new Foo,Bar or Fiz, depending on the actual object type.
}
}
class Bar: public Foo{
public:
Bar(){
}
}
class Fiz: public Foo{
public:
Fiz(){
}
}
在基类中是否可以使用
createOb()
方法,因此在其中一个派生类的实例上调用createOb()时,就可以创建派生类的实例吗? 最佳答案
是的,可以使用CRTP完成。
首先,返回从new
获得的原始指针是,非常危险。在c++
中,仅当原始指针不具有指向对象的所有权时,才应使用原始指针。因此,我自由使用了unique_ptr
:
struct Base {
virtual auto create_obj() -> std::unique_ptr<Base>
{
return std::unique_ptr<Base>{};
}
};
// abstract works too:
struct Base {
virtual auto create_obj() -> std::unique_ptr<Base> = 0;
};
template <class Derived>
struct Base_crtp : Base {
auto create_obj() -> std::unique_ptr<Base> override /* final */
{
return std::unique_ptr<Base>{new Derived{}};
}
};
struct D1 : Base_crtp<D1>
{
};
struct D2 : Base_crtp<D2>
{
};
进而:
auto b1 = std::unique_ptr<Base>{new D1{}};
auto b2 = std::unique_ptr<Base>{new D2{}};
auto new_d1 = b1->create_obj();
auto new_d2 = b2->create_obj();
关于c++ - 是否可以在同一类中创建一个类的实例?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39225474/