2015-12-14 179 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