[c++] Union (공용체) 본문

객체지향프로그래밍 (C++)

[c++] Union (공용체)

미니모아 2020. 7. 7. 16:05
반응형

가장 큰 멤버 변수 사이즈로 할당

union JobUnion {
    char name[32];
    float salary;
    int workerId;
}uJob;
struct JobStruct {
    char name[32];
    float salary;
    int workerId;
}sJob;
int main() {
    cout << sizeof(uJob) << endl;
    cout << sizeof(sJob) << endl;
    return 0;
}

union은 한 공간을 공유함

union JobUnion {
    long salary;
    int workerId;
}uJob;
struct JobStruct {
    long salary;
    int workerId;
}sJob;
int main() {
    //cout << sizeof(uJob) << endl;
    //cout << sizeof(sJob) << endl;
    uJob.salary = 11;
    uJob.workerId = 1234;

    sJob.salary = 21;
    sJob.workerId = 4567;

    cout << uJob.salary << endl;//1234
    cout << uJob.workerId << endl;//1234
    cout << sJob.salary << endl;//21
    cout << sJob.workerId << endl;//4567
    return 0;
}
반응형

'객체지향프로그래밍 (C++)' 카테고리의 다른 글

[c++] void pointer (void 포인터)  (0) 2020.07.07
[c++] 데이터 표현  (0) 2020.07.07
[c++] structor(구조체)  (0) 2020.07.07
[c++] Pointer (포인터)  (0) 2020.07.07
[c++] inline variable  (0) 2020.07.07
Comments