我創建了一個使用聯盟作爲其字段的結構。這裏是一個小的代碼示例:分配聯盟的字段
#include <iostream>
#include <string>
enum Type
{
STR,
INT
};
struct MyStruct
{
Type type;
union Value
{
std::string str;
int i;
Value(){}
~Value(){};
} value;
void setType(Type type)
{
this->type = type;
}
void setValue(const std::string& data)
{
this->value.str = data;
}
MyStruct(){}
~MyStruct(){}
};
int main()
{
MyStruct my;
my.setType(Type::STR);
my.setValue("Hallo");
std::cout << my.value.str << std::endl;
return 0;
}
設置值,我得到一個錯誤(分段故障(核心轉儲))什麼是這樣做的正確方法?謝謝!
將int與一個字符串聯合起來是個可怕的想法。 – user3528438
你的'union'可能有一個數據成員,它有一個非平凡的特殊成員函數。請參閱:[鏈接](http://en.cppreference.com/w/cpp/language/union) – knivil
您不應該有單獨的'setType'和'setValue'函數,而應該一次性設置(因爲您需要檢查現有類型以瞭解是否需要調用構造函數和析構函數)。你最好查看如何使用包含字符串的聯合的示例代碼,而不是猜測/發佈問題。 –