在文件 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/