与并集和结构混淆

confusion with union and struct

本文关键字:结构      更新时间:2023-10-16

我正在PCL(Point Cloud Library,www.pointclouds.org)中进行一个项目有了这个库,我可以获得Kinect正在观看的内容的3D表示。问题是,我使用的是这个结构:

typedef union
{
    struct
    {
            unsigned char Blue;
            unsigned char Green;
            unsigned char Red;
            unsigned char Alpha;
    };
    float float_value;
    uint32_t long_value;
} RGBValue;

我想对这个结构做的是从每种颜色中获得单独的数据,并将它们放在浮动中:

float R = someCloud->points[idx].rgba.Red;   
float G = someCloud->points[idx].rgba.Green;  
float B = someCloud->points[idx].rgba.Blue;  
float A = someCloud->points[idx].rgba.Alpha;  

我得到的错误是:

error C2039: 'Red' : is not a member of 'System::UInt32'*

您必须相应地命名您的匿名结构实例

typedef union
{
    struct
    {
        unsigned char Blue;
        unsigned char Green;
        unsigned char Red;
        unsigned char Alpha;
    } rgba;
    float float_value;
    uint32_t long_value;
} RGBValue;

然后,您可以作为访问成员

RGBValue v;
float R = v.rgba.Red;
float G = v.rgba.Green;
float B = v.rgba.Blue;
float A = v.rgba.Alpha;

这:

typedef union
{
    struct
    {
        unsigned char Blue;
        unsigned char Green;
        unsigned char Red;
        unsigned char Alpha;
    };
    float float_value;
    uint32_t long_value;
} RGBValue;

声明了一个带有嵌套结构的联合类型。联合只包含floatuint32_t-您从未声明嵌套结构的实例

你可以给你的类型起一个名字,这样你就可以在其他地方使用它:

typedef union
{
    struct RGBA // named struct type
    {
        unsigned char Blue;
        unsigned char Green;
        unsigned char Red;
        unsigned char Alpha;
    };
    RGBA rgba; // AND an instance of that type
    float float_value;
    uint32_t long_value;
} RGBValue;

或者保持类型匿名,只声明一个实例,如Olaf所示。(在我的示例中,命名类型可以称为RGBValue::RGBA