访问union的成员变量:为uint64声明,但在uint32中需要一些东西。 C ++

时间:2017-09-21 01:49:12

标签: c++ unions

假设我想分配一些随机值,并且在uint32_t中返回随机值的唯一选项。我想将该值赋给uint64_t中的某个union变量。所以我做了以下工作,但是没有用。

#include <iostream>
#include <random>
#include <time.h>       /* time */

class A{
public:
    A(){
        srand (time(NULL));
        A_ = rand(); // Also error
        // What i want ::
        // A_.A32 = rand();
    }

    union A_{
        uint64_t A64_;
        struct  A32{
            uint32_t a32_1;
            uint32_t a32_2;
        };
    };
};

int main(){
    A a;
}

如何解决uint32_t中无法使用某些内容的问题,例如将某些uint32_t值分配给a32_1或a32_2?

错误信息如下:

g++ -std=c++14 -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -        MF"src/myNeo.d" -MT"src/myNeo.d" -o "src/myNeo.o" "../src/myNeo.cpp"
../src/myNeo.cpp:57:6: error: expected unqualified-id

1 个答案:

答案 0 :(得分:1)

您的A_声明定义了一种类型,而不是变量。您需要一个变量来写入,例如:

#include <iostream>
#include <random>
#include <time.h> /* time */

class A {
public:
    A() {
        srand (time(NULL));
        u.U32_1 = rand();
        u.U32_2 = ...;
    }

    union U {
        uint64_t U64;
        struct {
            uint32_t U32_1;
            uint32_t U32_2;
        };
    };

    U u;
};

int main() {
    A a;
}

另一方面,如果您的目标只是将32位整数转换为64位整数,则可以按原样分配它,让编译器为您扩展值:

#include <iostream>
#include <random>
#include <time.h> /* time */

class A {
public:
    A() {
        srand (time(NULL));
        u = rand();
    }

uint64_t u;
};