为什么不能将具有 return 值的函数分配给具有 void 的指针函数?

Why can't a function with return value be assigned to a pointer function with void?

在 C/C++ 中,下面的代码工作得很好。

void *pa;
void fa(void*);

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

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

   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的return类型可以很好的丢弃(即直接调用fb()而不使用它的return值),为什么标记的那一行没有工作?

为此,编译器仍然会抱怨。

   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().

,编译器将无法知道有一个需要删除的返回值

关于你的第三个案例:

"function that returns int*" 与 returns void*.
的“函数完全无关 如果您尝试

,您会看到同样的错误
char f(); 
int(*p)() = f;

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

return 为 int 的函数不是 return 为 void 的函数。您可以调用函数并忽略其 return 值,但是当您创建指向函数的指针时,类型必须完全匹配。要在需要 return 为 void 的内容的上下文中使用 return 为 int 的函数,请使用 std::function;它处理参数和 return 类型中的阻抗不匹配。