将 void* 转换为其他类型

标签 c casting

我收到错误:

error: 'void*' is not a pointer-to-object type

对于以下代码:

Button config_b1 = Button("b1");
Button config_b2 = Button("b2");
Button config_b3 = Button("b3");

const void *const buttons[3] PROGMEM = {
&config_b1, &config_b2, &config_b3
};

在某些功能中:

(Button)*buttons[1]->setText("Foo");

转换为 Button 失败。

这只是一个简化的示例。数组“按钮”将具有不同类型的对象,因此我需要将其初始化为 void,然后在函数内转换为正确的类型。

最佳答案

我认为这是一个简单的优先级错误,您需要

((Button *) buttons[1])->setText("foo");

顺便问一下,你确定这是C吗?这种调用确实看起来像 C++(也可能是 C,但在大多数情况下您需要显式的 this 等效项)。

关于将 void* 转换为其他类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44135142/

相关文章:

c - 内核如何知道哪些驱动程序属于哪些外设?

c - 不同平台上的打印类型有所不同

C 或 C++ 堆内存管理实现

c - 为什么 gcc 给我这个结果?

c++ - boost lexical_cast <int> 检查

c++ - 将右值引用参数转换为右值引用?

c - 将 printf 用于 char 时仅输出点

mysql 如何将 group_concat() 结果放入列表中

c++ - 将数组作为结构体访问与未定义的行为

c++ - int to void* - 避免 c 风格的转换?