C++:将结构类型更改为 child 类型

C++: Changing type of a struct to child type

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

struct parent {
...
};
struct childA : parent {
...
};
struct childB : parent {
...
};
struct childC : parent {
...
};

我有以下 class:

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

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

switch (input) {
case 0:
    childA myStruct;
    break;
case 1:
    childB myStruct;
    break;
case 2:
    childC myStruct;
    break;
}

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

您不能更改对象的类型。那是不可变的。

您正在寻找的是一个工厂,用于根据输入选择要创建的对象类型:

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