2017-12-17 3 views
0

나는이 열거, 노동 조합 및 구조체가 : 나는 동적으로 다른 변수에 따라 노동 조합 내부 변수에 액세스하는 방법을 알고 싶습니다접근 노조가 동적으로

union num { 
    int i; 
    short s; 
    float f; 
    double d; 
}; 
enum tag {SHORT, INT, FLOAT, DOUBLE}; 
struct vrnumber { 
    num num; 
    tag type; 
}; 

(즉 사용자의 입력). (즉) 유니온의 변수로 특정 연산을 만들고 싶습니다.하지만 런타임 중에 액세스 할 유니온 변수를 알고 싶습니다. 그래서 대신 같은 더 좋은 방법이 될 것이다 : 나는 모든 경우에 그것이 내가 저장하거나 값을 사용 노조에 액세스 할 때 유일한 차이점은 동일한 작업을하는 동안 매우 길고 중복 생각

vrnumber m; 
switch (m.type) { 
    case SHORT: //an operation .. 
    case INT: //same operation ... 
    case FLOAT: //same operation ... 
    case DOUBLE: //same operation ... 
} 

.

+0

마지막으로 쓰여진 유니온 이외의 유니온에서 읽는 것은 정의되지 않은 동작입니다. 노조를 왜 사용하고 싶은지 설명 할 수 있습니까? –

+3

[변형 유형] (https://en.wikipedia.org/wiki/Variant_type)을 만들려고하는 것 같습니다. 이 디자인 패턴의 기존 예제가 많이 있습니다. – MrEricSir

답변

1

이렇게하는 방법은 구조체 정의에서 사용할 연산자를 정의하는 것입니다. 운영자 -가 사용하려고하는 경우 예를 들어, 이러한 방법을 정의

struct vrnumber { 
    num num; 
    tag type; 

    //between vrnumbers 
    vrnumber operator- (const vrnumber& rhs); 

    //vrnumbers and basic types 
    vrnumber operator- (const int& rhs); 
    vrnumber operator- (const double& rhs); 

    //if vrnumber is used as rhs 
    friend vrnumber operator- (const int& lhs, const vrnumber& rhs); 
    friend vrnumber operator- (const double& lhs, const vrnumber& rhs); 
}; 

이러한 이러한 방법 중 일부의 정의의 예이다 : 여기

vrnumber vrnumber::operator- (const vrnumber& rhs){ 
    switch(type){ 
     case SHORT: 
      switch(rhs.type){ 
       //...... 
       //cases here 
     } 
     //...... 
     //cases here 
    } 
} 
vrnumber vrnumber::operator- (const int& rhs){ 
    switch(type){ 
     case SHORT: return num.s-rhs; 
     case INT: return num.i-rhs; 
     case FLOAT: return num.f-rhs; 
     case DOUBLE: return num.d-rhs;   
    } 
} 
vrnumber operator- (const int& lhs, const int& rhs){ 
    switch(rhs.type){ 
     //.......... 
     //...cases, same as the others 
    } 
} 

이러한 동작의 예는 넣어 사용법 :

vrnumber m1; 
vrnumber m2; 
int i1; 
float f1; 
//the example: 
m1=f1-(m1-m2)-i1; 

이 접근법을 사용하는 경우 장황한 연산자 정의가 사용됩니다. 그러나 이런 종류의 작업이 코드에서 번이 LOT 번이라면 코드가 짧아지고 단순해질 수 있습니다.