什么是用例匿名联合类型 [英] What is the use case for an anonymous union type

查看:118
本文介绍了什么是用例匿名联合类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个看到了下面的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;

这篇关于什么是用例匿名联合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆