问题描述
一个看到了下面的code的一个问题:
A saw a question with the following code :
union
{
float dollars;
int yens;
}price;
价格
是一个变量,其类型没有名称。
什么是这样一个未命名的类型有用吗? LAMBDA前pressions?
在C和C ++?
price
is a variable whose type does not have a name.What is such an unnamed type useful for? Lambda expressions?Is this valid in both C and C++?
推荐答案
这类型不具有名称对使用价格
的影响很小的事实变量。它的意思是,你不能(容易)创建此类型的另一个对象。
The fact that the type does not have a name has very little effect on the use of the price
variable. All it means is that you cannot (easily) create another object of this type.
此构造是很有道理的,如果价格
是函数内的局部变量。如果您只想这种类型的一个对象,你并不需要命名的类型,何必呢。它没有什么不同都来自:
This construct makes the most sense if price
is a local variable inside a function. If you only ever want one object of this type, you don't need to name the type, so why bother. It doesn't differ at all from:
union SomeNameIPromiseNotToUseAnywhereAndWhichDoesntConflictWithAnything
{
float dollars;
int yens;
} price;
注意在C ++ 11及以后,你的可以的实际创建另一个对象:
Notice that in C++11 and beyond, you can actually create another object:
decltype(price) anotherPrice;
这篇关于什么是用例匿名联合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!