【问题标题】:Invalid cast from type 'float' to type 'float*' [duplicate]从“float”类型到“float *”类型的无效转换[重复]
【发布时间】: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 用于向下转换多态类型。

标签: c++ pointers types any


【解决方案1】:

您不应该从随机类型转换为指针类型。尽管转换 char const *intbool 似乎对您有用,但它们并不是您想要的,而不是将 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。

【讨论】:

  • 有效!非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多