簡體   English   中英

訪問union的成員變量:為uint64聲明,但在uint32中需要某些內容。 C ++

[英]Accessing union's member variable: declared for uint64, but want something in uint32. c++

假設我要分配一些隨機值,並且該隨機值的唯一選項在uint32_t中返回。 我想將該值分配給uint64_t中的一些並集變量。 因此,我執行以下操作,但這不起作用。

#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

您對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;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM