2013-06-21 6 views
-4

모든 유형의 개체를 만들려고합니다.형식이 'float'이고 유형이 'float *'인 유효하지 않은 캐스트

#include <stdio.h> 

class thing 
{ 
public: 
    void *p; 
    char type; 

    thing(const char* x) 
    { 
     p=(char*)x; 
     type=0; 
    } 

    thing(int x) 
    { 
     p=(int*)x; 
     type=1; 
    } 

    thing(bool x) 
    { 
     p=(bool*)x; 
     type=2; 
    } 

    /* 
    thing(float x) 
    { 
     p=(float*)x; 
     type=3; 
    } 
    */ 

    void print() 
    { 
     switch(type) 
     { 
     case 0: 
      printf("%s\n", p); 
      break; 
     case 1: 
      printf("%i\n", p); 
      break; 
     case 2: 
      if(p>0) 
       printf("true\n"); 
      else 
       printf("false\n"); 
      break; 
     case 3: 
      printf("%f\n", p); 
      break; 
     default: 
      break; 
     } 
    } 
}; 

int main() 
{ 
    thing t0("Hello!"); 
    thing t1(123); 
    thing t2(false); 

    t0.print(); 
    t1.print(); 
    t2.print(); 

    return 0; 
} 

코드가 작동하고 나는이 프로그램을 실행하면, 그것은 표시 : 여기 코드는

Hello! 
123 
false 

을하지만 플로트 생성자의 주석을 해제하는 경우, 컴파일러는 다음과 같은 오류 기록 :

main.cpp: In constructor 'thing :: thing (float)': main.cpp: 30:13: 
error: invalid cast from type 'float' to type 'float *' 

왜 float 유형으로 작동하지 않습니까? 다음을 사용합니다 : Windows XP SP3, MinGW GCC 4.7.2.

+4

'boost :: any'를 사용하지 않는 이유는 무엇입니까? – chris

+0

캐스팅하려는 값의 ADDRESS를 포인터로 저장 하시겠습니까? 부동 소수점 값을 포인터로 저장할 수 없습니다. –

+1

'p = (float *) x'; 당신은 float *으로 float을 캐스팅합니다. –

답변

2

임의 유형에서 포인터 유형으로 변환하지 않아야합니다. 주조 char const *, intbool을 캐스팅하더라도 더 이상 플로트를 포인터로 캐스팅하는 것보다 원하는 것이 아닙니다. 실제로 C++의 캐스트를 잘못 표시 할 수 있다는 경고 표시로보아야합니다.

대신 다음과 같이해야합니다.

class thing { 
private: 
    union { 
    char const *cs; 
    int i; 
    bool b; 
    float f; 
    }; 
    enum class type { cs, i, b, f } stored_type; 

public: 

    thing(const char* x) : cs(x), stored_type(type::cs) {} 
    thing(int x)   : i(x), stored_type(type:: i) {} 
    thing(bool x)  : b(x), stored_type(type:: b) {} 
    thing(float x)  : f(x), stored_type(type:: f) {} 

    void print() 
    { 
    switch(stored_type) 
    { 
    case type::cs: 
     std::printf("%s\n", cs); break; 
    case type::i: 
     std::printf("%i\n", i); break; 
    case type::b: 
     std::printf("%s\n", b ? "true" : "false"); break; 
    case type::f: 
     std::printf("%f\n", f); break; 
    } 
    } 
}; 

또는 더 나은 아직 당신은 이미 변형 :: 부스트로, 당신을 위해이 작업을 수행 라이브러리를 사용하거나 부스트 : 어떤 수 있습니다.

+1

그것은 작동합니다! 고맙습니다. – mrsimb