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

标签 c++ inheritance struct assign

在文件 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 的类型更改为其子类型之一?因为 myStruct 需要在构造函数之外访问,所以我想在类的头中将其声明为父类型,并在构造函数中将其类型更改为子类的类型。

最佳答案

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

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

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

关于C++:将结构的类型更改为子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34274978/

相关文章:

c++ - extern"C"与 extern 的区别

c++ - 在C++中推导继承方法的父类

inheritance - 你为什么要对整个类(class)进行密封/最终定级?

struct - Julia 可变结构中的变量字段名

struct - 为 Rust 新类型自动实现封闭类型的特征(具有一个字段的元组结构)

c++ - 从用户那里获得无限量的输入,而不是打印最大的 3 ,而不使用数组

c++ - 为什么 C++ 没有虚拟变量?

c++ - 如何在 header 中声明一个新类并在源文件中定义它而不会出现此错误?

c# - 为什么写入 24 位结构不是原子的(当写入 32 位结构时似乎是)?

c++ - C++11 中的 constexpr 概念