gpt4 book ai didi

c++ - int(*g)(int) 转换为 int(*h)(char) 导致错误的原因?

转载 作者:行者123 更新时间:2023-12-03 06:51:30 26 4
gpt4 key购买 nike

我正在学习编程语言原理,我有一个关于 C 和 C++ 的问题。

int (*f)(int);
int (*g)(int);
int (*h)(char);

f = g; // ok
h = g; // warning in C, error in C++
分配 g进入 f ( f = g ) 在 C 或 C++ 中不会导致错误,但会分配 g进入 h ( h = g ) 将在 C 中生成编译器警告并在 C++ 中生成编译错误。
听说 char类型通常自动转换为 int在 C++ 中,所以我认为这不会导致错误。
谁可以给我解释一下这个?

最佳答案

Assigning g into f (f = g) will not cause an error in C/C++, but assigning g into h (h = g) would generate a compiler warning in C and compile error in C++.


这是不正确的。一个试图做的程序 h = g是无效程序,无论是 C 还是 C++。然而,C 标准明确提到允许 C 编译器成功编译无效程序,前提是它为每次违反某些规则发出诊断消息。您收到了警告,然后 C 编译器仍然继续进行。
事实上,C++ 标准包含一个非常相似的措辞:

If a program contains a violation of any diagnosable rule or an occurrence of a construct described in this document as “conditionally-supported” when the implementation does not support that construct, a conforming implementation shall issue at least one diagnostic message.

[...]

A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any well-formed program. Implementations are required to diagnose programs that use such extensions that are ill-formed according to this document.Having done so, however, they can compile and execute such programs.


但是通常 C++ 编译器在默认情况下在可诊断的违规方面更加严格,并且默认情况下编译会失败,而来自同一供应商的 C 编译器会成功编译这样的翻译单元。

请注意,C 和 C++ 都规定您可以使用强制转换进行转换,即 h = (int (*)(char))g ;但你不能再通过 h 调用函数无需将其返回到 int (*)(int)第一的!

关于c++ - int(*g)(int) 转换为 int(*h)(char) 导致错误的原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64751866/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com