c++ - 为什么不能将具有返回值的函数赋值给具有 void 的指针函数?

标签 c++ casting function-pointers void-pointers

在 C/C++ 中,以下代码工作得非常好。

void *pa;
void fa(void*);

int a; // or any type
pa = &a;
fa(&a);

我很困惑为什么函数的返回类型不是这样:

   void fa(void);
   int fb(void);
   void (*pa)(void);
   int (*pb)(void);

   pa = fa; pb = fb; // OK
-> pa = fb; // Wrong, why???
   pb = fa; // Wrong, but reasonable

既然fb的返回类型可以很好的丢弃(即直接调用fb()而不使用它的返回值),为什么标记的那行不行呢?

为此,编译器仍然会提示。

   void* fa(void);
   int* fb(void);
   void* (*pa)(void);
   int* (*pb)(void);

   pa = fa; pb = fb; // OK
-> pa = fb; // Wrong, why???
   // pb = fa;

[Error] invalid conversion from 'int* (*)(void)' to 'void* (*)(void)' [-fpermissive]

我完全不知道为什么...

最佳答案

即使您的源代码忽略了返回值,它仍然是函数调用时返回的值,编译器必须生成代码来处理它。
换句话说:它只会在源代码中被忽略,而不会被执行程序忽略。

如果你有

int fa() {return 0;}
//...
something();
fa();
somethingelse();

相当于

int fa() {return 0;}
//...
something();
{  // Scope that delimits the returned value's lifetime.
    int imgonnaignorethismmkay = fa();
} // End special scope, destroy the return value.
somethingelse();

如果pa = fb如果您调用 pa(),编译器将无法知道有一个需要删除的返回值.


第三种情况:

“返回 int* 的函数”与“返回 void* 的函数”完全无关。
如果你尝试,你会看到同样的错误

char f(); 
int(*p)() = f;

即使您可以将 char 转换为 int。

关于c++ - 为什么不能将具有返回值的函数赋值给具有 void 的指针函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45506937/

相关文章:

java - 调用 'Class.forName' 时未选中强制转换警告

空指针和指向函数指针的指针之间的转换

linux - 函数指针指向 struct "proto_ops"的哪里?

c++ - 选择 2D xtensor 的特定行

c++ - 为什么我的代码会因为在函数内部声明带有显式构造函数的静态对象而崩溃?

c++ - 底层 STL:在没有新 vector 的情况下将 std::vector 连接到自身

ios - 使用 Swift 将数据保存到 Firebase

typescript 只采用接口(interface)中定义的属性

c++ - 正确使用 std::tuple?

c++ - 如何从二进制数据调用函数