一看到一個問題用下面的代碼:什麼是用例匿名聯合型
union
{
float dollars;
int yens;
}price;
price
是一個變量,其類型沒有名稱。 什麼是這樣一個未命名的類型有用? Lambda表達式? 這對C和C++都有效嗎?
一看到一個問題用下面的代碼:什麼是用例匿名聯合型
union
{
float dollars;
int yens;
}price;
price
是一個變量,其類型沒有名稱。 什麼是這樣一個未命名的類型有用? Lambda表達式? 這對C和C++都有效嗎?
的類型沒有名稱,這一事實對使用price
變量的影響非常小。它意味着你不能(容易地)創建這種類型的另一個對象。
如果price
是函數內部的局部變量,則此構造最有意義。如果你只想要一個這種類型的對象,你不需要命名該類型,所以爲什麼要麻煩。它沒有什麼不同,在全部來自:
union SomeNameIPromiseNotToUseAnywhereAndWhichDoesntConflictWithAnything
{
float dollars;
int yens;
} price;
請注意,在C++ 11及以後,你可以實際上創建另一個對象:
decltype(price) anotherPrice;
在C++中,它是有效的。代碼定義了一個名爲price的局部變量,它可以存儲整數值yens
或浮點值dollars
。不知道它是如何使用的,我只能斷定變量是一個本地/臨時變量(並且可能在一個試圖做得太多的函數中)。
實施例:
union
{
float dollars;
int yens;
} price;
if(currency != "USD")
price.yens = ConvertToYEN(fullPrice);
else
price.dollars = GetUpdatedPriceInUSD(abc, currency);
if(currency == "YEN")
std::cout << "Using price in yens: " << price.yens << "\n";
根據該鏈接
https://gcc.gnu.org/onlinedocs/gcc/Unnamed-Fields.html#Unnamed-Fields
可以只訪問該聯盟的成員等price.dollars
和price.yens
因爲price
已經類型的可變
在C並且不需要創建同一類型的新對象。
union
{
float dollars;
int yens;
}price;
int main(void) {
price.dollars = 90.5;
printf("%f\n",price.dollars);
price.yens = 20;
printf("%d\n",price.yens);
return 0;
}
我在過去所用的工會處理存儲格式並在它們之間進行翻譯的機制。
例如,它可能是程序包含以浮點格式存儲文件數量的代碼,並且存儲函數接受/返回浮點數。後來發現我們需要使用一個整數,所以我們只需使用聯合就可以以我們所知的格式訪問數據。例如:
price.dollars = load_from_file();
if (yen_flag)
// use price.yen
else
// use price.dollars
它也常用於實現獨立存儲整數。
union {
int int_val;
char as_bytes[4];
} int_store;
對不起,如果有任何語法錯誤,這是一段時間...
我看到這樣的代碼在2D/3D計算數學圖書館的很多:
struct Matrix3x3
{
union
{
struct
{
float m00 , m01 , m02;
float m10 , m11 , m12;
float m20 , m21 , m22;
};
float m[ 3 ][ 3 ];
};
};
IIRC,我讀的地方,使用這種方法會導致違反嚴格別名規則
struct FooBar
{
union
{
Foo foo;
char dummy[128];
};
Bar bar;
};
我見過有人用無名聯合來控制struct
成員的偏移量。
將struct
成員與某個邊界對齊沒有簡單的方法,但可以將struct
的開頭對齊到任意邊界,然後將該成員填充到下一個邊界。
這完全不重複,typedef的位置與您提供的鏈接相同? – 2015-03-25 08:30:10
其他(某些其他數據)會告訴哪個工會成員使用。你真的應該顯示更多的代碼,並選擇C和C++(這是不同的語言)。所以問一個新問題或強烈編輯這個問題。 – 2015-03-25 08:32:56
@BasileStarynkevitch問題的核心不是「什麼是工會?」但「爲什麼這種工會類型沒有名字,爲什麼?」 – Angew 2015-03-25 08:33:34