从类型"浮点数"到类型"浮点数*"的转换无效
Invalid cast from type 'float' to type '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("%sn", p);
break;
case 1:
printf("%in", p);
break;
case 2:
if(p>0)
printf("truen");
else
printf("falsen");
break;
case 3:
printf("%fn", 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。
您不应该从随机类型强制转换为指针类型。尽管强制转换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("%sn", cs); break;
case type::i:
std::printf("%in", i); break;
case type::b:
std::printf("%sn", b ? "true" : "false"); break;
case type::f:
std::printf("%fn", f); break;
}
}
};
或者更好的是,你可以使用一个已经为你做了这件事的库,比如boost::variant或boost::any。
相关文章:
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何将浮点数(*)[6]转换为浮点**类型?
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- Zedboard zynq-7000 Opencl 浮点数从类型 'double*' 强制转换为类型 'double' 无效
- 从浮点数中删除小数部分但保留类型的有效方法
- 在 OpenCL 内核中实现半精度浮点数据类型
- 如何随机化双精度/浮点数据类型? C++
- 当没有浮点数据类型时,为什么此代码会出现浮点异常
- 如何计算浮点数据类型的范围、最大值、最小值
- 根据浮点数选择最小整数类型
- 为什么这种类型是双精度而不是浮点数
- 错误:请求从 std::chrono::time_point 浮点数转换为非标量类型长整型
- 将 32 位浮点数和不强制转换的 32 位整数与双精度进行比较,当其中一个值可能太大而无法完全适合另一种类型时
- 当浮点数文本直接分配给不同的类型时,编译器如何处理浮点文字?
- C++ 中浮点数据类型的精度
- 为什么 std::bitset 只支持整型数据类型?为什么不支持浮点数?
- 对浮点数求和会因类型转换而失去精度
- 如何获取模板的类型,如模板<类型名 T>,并检查 T 是 int 还是浮点数或类
- C++11 类型推理如何在浮点数或双精度数之间做出决定
- 从类型"浮点数"到类型"浮点数*"的转换无效