C++:将结构的类型更改为子类型

Exu*_*des 2 c++ inheritance struct assign

在文件database.h中,我有以下结构:

struct parent {
...
};
struct childA : parent {
...
};
struct childB : parent {
...
};
struct childC : parent {
...
};
Run Code Online (Sandbox Code Playgroud)

我有以下课程:

class myClass {
    parent myStruct;
    ...
    myClass(int input) {
        switch (input) {
        //
        // This is where I want to change the type of myStruct
        //
        }
    };
    ~myClass();
}
Run Code Online (Sandbox Code Playgroud)

本质上,在myClass的构造函数中,我想根据输入更改myStruct的类型:

switch (input) {
case 0:
    childA myStruct;
    break;
case 1:
    childB myStruct;
    break;
case 2:
    childC myStruct;
    break;
}
Run Code Online (Sandbox Code Playgroud)

但是,我还没有找到适用于此的解决方案.如何将myStruct的类型更改为其类型的子类型?因为myStruct需要在构造函数外部可访问,所以我想在类的头中将其声明为类型parent,并将其类型更改为构造函数中的子类型.

Bar*_*rry 7

您无法更改对象的类型.这是不可改变的.

您正在寻找的工厂是根据其输入选择要创建的对象类型:

std::unique_ptr<parent> makeChild(int input) {
    switch (input) {
    case 0: return std::make_unique<child1>();
    case 1: return std::make_unique<child2>();
    ...
    }
}
Run Code Online (Sandbox Code Playgroud)