gpt4 book ai didi

C++ 函数声明

转载 作者:太空狗 更新时间:2023-10-29 23:06:12 26 4
gpt4 key购买 nike

我是 C++ 的新手。我不明白为什么 1 个函数被声明两次是可以的(即为什么编译器允许它)。比如下面的代码是合法的:

#include <iostream>
#include <string>

int hello();
int hello();

int main(){
cout << "hello, world" << endl;
}

int hello(){
return 1;
}

为什么编译器不报错?

最佳答案

在 C 和 C++ 中,前向声明非常弱。它们向编译器提供正式的“ promise ”,即如果具有指定签名的函数出现,它将具有您指定的签名。该函数甚至不能保证出现:除非您调用或以其他方式引用声明的函数,否则编译器不会提示存在没有定义的声明。该标准要求编译器将相同的前向声明视为单个声明。

不同于根据单一定义规则必须唯一的定义

3.2 No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, or template

声明只需要引用相同的定义,即彼此等价:

3.3.4 Given a set of declarations in the same declarative region, each of which specifies the same unqualified name, they shall all refer to the same entity, or all refer to functions or function templates, [...]

关于C++ 函数声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16642027/

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