c++ union memory question

Asked 6 days ago, Updated 6 days ago, 1 views

struct RECT
{
    LONG    left;
    LONG    top;
    LONG    right;
    LONG    bottom;
} 

struct Rect
{
    Rect(RECT r) {
        memcpy(&data, &r, sizeof(RECT));
    }
    operator RECT() const { return data; }
    union 
    {
        //LONG d[4];
        LONG l,t,r,b;
        RECT data;
    };
};

Hello, everyone I want to use the two structures in compatibility, but I want to make the memory addresses of the variables of RECT and Rect the same.

Of course, the left top of REAC with d[0] d[1] can be replaced When I tried to write with Rect, t, r, b, the address was the same as the first RECT left Is there a way? I really want to make the right of RECT and r of Rect the same.


2022-09-20 14:55

1 Answers

Please refer to the code below and the result.

It's a simple code, so you'll understand right away.

#include <iostream>

using namespace std;

struct RECT {
    int left;
    int top;
    int right;
    int bottom;
};

struct Rect {
    Rect(RECT r) :data{ r } {}
    operator RECT() const { return data; }
    RECT data;
    int& l{ data.left };
    int& t{ data.top };
    int& r{ data.right };
    int& b{ data.bottom };
};

int main()
{
    RECT r{ 1,2,3,4 };

    Rect rr{ r };

    cout << &rr.data << '\n';
    cout << &rr.data.left << '\t' << &rr.l << '\n';
    cout << &rr.data.top << '\t' << &rr.t << '\n';
    cout << &rr.data.right << '\t' << &rr.r << '\n';
    cout << &rr.data.bottom << '\t' << &rr.b << '\n';

    RECT rrr = RECT(rr);
    cout << rrr.left << ',' << rrr.top << ',' << rrr.right << ',' << rrr.bottom << '\n';
}


2022-09-20 14:55

If you have any answers or tips


© 2022 pinfo. All rights reserved.