c/c++语言开发共享匿名联合类型的用例是什么?

A看到了以下代码的问题:

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的float值。

    在没有看到如何使用它的情况下,我只能得出结论,变量是一个本地/临时变量(可能在一个试图做太多的函数中)。

    例:

     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"; 

    我过去曾使用过工会作为处理存储格式和在它们之间进行转换的机制。

    例如,程序可能包含用于以浮动格式存储文件中的金额以及存储函数接受/返回浮点数的代码。 后来发现我们需要使用一个整数,所以我们只需使用union就可以以我们所知的格式访问数据。 例如:

     price.dollars = load_from_file(); if (yen_flag) // use price.yen else // use price.dollars 

    它也常用于实现独立的int存储。

     union { int int_val; char as_bytes[4]; } int_store; 

    对不起,如果有任何语法错误,它已经有一段时间了……

    在C中根据此链接

    您可以像price.dollarsprice.yens一样访问union的成员,因为price已经是union类型的变量,并且不需要创建相同类型的新对象。

     union { float dollars; int yens; }price; int main(void) { price.dollars = 90.5; printf("%fn",price.dollars); price.yens = 20; printf("%dn",price.yens); return 0; } 

    我在很多用于2D / 3D计算的数学库中看到了这样的代码:

     struct Matrix3x3 { union { struct { float m00 , m01 , m02; float m10 , m11 , m12; float m20 , m21 , m22; }; float m[ 3 ][ 3 ]; }; }; 

    另见这个Q.


    iirc,我在某处读过使用这种方法会导致违反严格的别名规则

     struct FooBar { union { Foo foo; char dummy[128]; }; Bar bar; }; 

    我见过人们使用无名联合来控制struct成员的偏移量。

    struct成员与某个边界对齐没有什么简单的方法,但是有一些方法可以将struct的开头对齐到任意边界,然后将成员填充到下一个边界。

      以上就是c/c++开发分享匿名联合类型的用例是什么?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/559925.html

      (0)
      上一篇 2021年1月27日
      下一篇 2021年1月27日

      精彩推荐