c++ - 如何在构造函数中将基类实例化为派生类?

标签 c++ class oop inheritance constructor

在基类构造函数中,我希望实例是派生类。我可以做这样的事情吗?

class InterfaceClass // Final user only sees this class
{ 
    enum class TYPE 
    {
        CHILDONE
    };

public:
    InterfaceClass(TYPE);
    virtual void hello_world() = 0;
    virtual void print_class();
};

class ChildOne : public InterfaceClass 
{
public:
    ChildOne() = default;
    void hello_world();
private:

};

InterfaceClass::InterfaceClass(TYPE type) 
{
    if (type == CHILDONE)
        this = new ChildOne();
    else
        throw "NOT HANDLED";
}

void InterfaceClass::hello_world() {
    std::cout << "Hello world from InterfaceClass" << std::endl;
}

void InterfaceClass::print_class() {
    std::cout << "Not implemented" << std::endl;
}

void ChildOne::hello_world() {
    std::cout << "Hello world from ChildOne" << std::endl;
}

// Final user will see only declaration of InterfaceClass
int main()
{
    InterfaceClass* ic = new InterfaceClass(InterfaceClass::TYPE::CHILDONE);
    ic->hello_world();
}

我想构建一个像这样的架构。 但我不知道如何正确地做到这一点。

最佳答案

I would like to instantiate A as a child, depending on an enum given in the constructor [...]

这个

this = new ChildOne();

没有任何意义。 this pointer is a prvalue ,您不能为其分配任何内容。从描述来看,您似乎需要一个返回派生类的工厂函数,具体取决于枚举 TYPE .

#include <memory> // std::unique_ptr

std::unique_ptr<InterfaceClass> InterfaceClass::createInstance(TYPE type) 
{
    switch (type) {
    case TYPE::CHILDONE:
        // use smart pointer instead the raw pointers
        return std::make_unique<ChildOne>();  
    // ... more
    default:
        throw "NOT HANDLED";
    }
}

此外,底座 InterfaceClass class required a virtual析构函数,以便删除通过 InterfaceClass 派生的类指针(即 std::unique_ptr<InterfaceClass>createInstance 中返回),执行定义的行为。

简而言之,你可能会这样做

#include <memory>

class InterfaceClass 
{
public:
    enum class TYPE
    {
        CHILD_ONE
        // .... CHILD_TWO 
    };

    virtual ~InterfaceClass() {} // required for defined behavior!
    virtual void hello_world() = 0;
    virtual void print_class() = 0;

    static std::unique_ptr<InterfaceClass> createInstance(TYPE type);
};

class ChildOne : public InterfaceClass 
{
public:
    void hello_world() override; // (Optionally) override the virtual functions
    void print_class() override; // (Optionally) override the virtual functions
}

See a demo in godbolt.org

关于c++ - 如何在构造函数中将基类实例化为派生类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76785807/

相关文章:

c++ - 如何为使用Clang LLVM编译的C++代码生成图形代码配置文件报告?

c++ - 将 "this"添加到 C++ 类实例化的 vector 中

c++ - 当我将一个类移动到头文件时,出现错误 C++

java - 关于固定类双重调度的问题

php - 动态类变量

c++ - 将 emscripten 与 opengl 着色器一起使用

c++ - 有没有办法让 C++ 从 cin 中接收未定义数量的字符串?

c++ - const 和 STL 容器

class - 如何在 UML 图中描述 Either/Or 继承?

c++ - 对象数组 C++