2015-12-14 180 views
2

更改结构的类型在文件database.h,我有以下结构:C++:儿童型

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

我有下面的类:

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; 
} 

但是,我没有被abl e找到适用于此的解决方案。我如何将myStruct的类型更改为其类型的子项之一?因为myStruct需要在构造函数之外访问,所以我想在类的头文件中将其声明为父类型,并将其类型更改为构造函数中的子类型。

+0

我想你想'的std ::的unique_ptr MYSTRUCT;' – Jarod42

回答

7

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

什么你要找的是一个工厂选择创建基于其输入的对象类型:

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

完美,只是我需要什么。谢谢 – Exudes