【发布时间】:2013-06-21 20:06:18
【问题描述】:
我正在尝试创建一个可以是任何类型的对象。代码如下:
#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
但是如果我取消注释 float 构造函数,编译器会写出以下错误:
main.cpp: In constructor 'thing :: thing (float)': main.cpp: 30:13:
error: invalid cast from type 'float' to type 'float *'
为什么它不适用于浮点类型? 我使用:Windows XP SP3、MinGW GCC 4.7.2。
【问题讨论】:
-
为什么不直接使用
boost::any? -
p=(float*)x;您正在将浮点数转换为浮点数*。 -
使用 C 样式转换是个坏主意。首选
static_cast进行一般转换,const_cast用于适当,reinterpret_cast用于绝对必要。您问题中的代码目前正在将您引向未定义行为的黑暗而可怕的道路。 -
@mrsimb 如果您使用联合来存储指针,请小心。它们只会存储指针,而不是底层数组/对象。如果您在字符串中包含
char *s,则该字符串本身将位于其他位置。 -
..和
dynamic_cast用于向下转换多态类型。