C++ 从类型';浮动';输入';浮动*';
我正在尝试创建一个可以是任何类型的对象。代码如下:C++ 从类型';浮动';输入';浮动*';,c++,pointers,types,any,C++,Pointers,Types,Any,我正在尝试创建一个可以是任何类型的对象。代码如下: #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; } thin
#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;
}
但是,如果我取消对浮点构造函数的注释,编译器将写入以下错误:
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。您不应该从随机类型强制转换为指针类型。即使对
char-const*
、int
和bool
进行强制转换似乎对您有效,但它们并不比将float转换为指针更符合您的需要。事实上,你应该查看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;
}
}
};
或者更好的是,您可以使用一个已经为您实现这一点的库,例如boost::variant或boost::any。为什么不直接使用
boost::any
?p=(float*)x
;您正在将浮点转换为浮点*。使用C样式转换是个坏主意。对于一般铸造,优先选择静态铸造
,常量铸造
在适当时,并在绝对必要时重新解释铸造。您问题中的代码目前正在引导您走向一条黑暗而可怕的未定义行为之路。@mrsimb如果您使用联合存储指针,请小心。它们只存储指针,而不存储底层数组/对象。如果你在字符串中有一个char*s
,那么字符串本身将在其他地方…并且dynamic\u cast
用于向下转换多态类型。它很有效!非常感谢你。
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;
}
}
};