2017-05-14 73 views
0

你好無情社區,今天我指望你的幫助。C++ Union/Struct'printColorPicker :: printColorPicker(void)':嘗試引用已刪除的函數

請不料小白的代碼

的錯誤是在第20行(我會發表評論,所以你可以看到)。

錯誤:「printColorPicker :: printColorPicker(無效)」:試圖引用刪除的功能

#include <iostream> 

    using namespace std; 

    enum availableColors { 
     incolorPrint, 
     colorPrint 
    }; 

    union printColorPicker { 
     struct incolorPrint { 
      int id; 
      char* details = "No color ink eh?"; 
     } i; 

     struct colorPrint{ 
      int id; 
      char* details = "Unicorn mode on"; 
     } c; 
    } color; //line 20 


    void colorPicker(availableColors c){ 
     char* option; 

     switch (c) { 
     case incolorPrint: { 
      option = color.i.details; 
     } 
     break; 

     case colorPrint: { 
      option = color.c.details; 
     } 
     break; 
     } 


     cout << option; 
    } 



    void main(){  
     colorPicker(colorPrint); 
    } 

什麼,我要做的是使用顏色選擇器的方法來呼應內/ COUT/printf的字符串printColorPicker聯盟內的結構(colorPrintincolorPrint)。

我得到了上面提到的錯誤。

+0

所以構造函數應該有'union'的名字,沒有參數? –

+0

TBH我不明白你爲什麼在你的代碼中使用'union'。 –

+0

這是一項功課,工會是其中的一項要求。 –

回答

0

我不熟悉union瘋狂,但可能發生的情況是,當您提供details的默認值時,您實際上提供了默認構造函數。 發生這種情況時, struct不再是聚合類型,也稱爲POD。這種非聚合傳播通過,聯合也不再是一個聚合類型,然後在構造上調用已刪除的默認構造函數。 (聚合類型不會在構造上調用構造函數,其行爲與C對象完全相同。)

編輯union只需要其構件是可以輕易構造的。通過提供默認值,struct將不再是可以輕易構造的。允許聚合類型爲private/protected成員的差異。

解決此問題的方法是刪除details的默認值並在構建後爲其分配(可能通過工廠功能)。

BTW爲union的不同對象設置默認值是沒有意義的,哪一個值應該是?

相關問題