我是 C++ 的新手,只是尝试一些东西。我坚持使用以下代码:
#include<iostream>
void t(){
std::cout << "func t()" << std::endl;
}
int main(int argc, char **argv) {
int t(); //declaration of function
std::cout << t() << std::endl;
}
输出是“func t()\n6295712”。我关心的是 t() 打印的随机数(?)。
我的问题是:为什么允许声明另一个返回类型的函数(此处:int 而不是 void)而不会出现任何错误?这不是违反类型安全,因为我从未定义过返回类型为“int”的函数吗?
使用的编译器:gcc (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4
最佳答案
我能找到的唯一相关内容是 [basic.scope.pdecl] 中的注释:
Function declarations at block scope and variable declarations with the extern specifier at block scope refer to declarations that are members of an enclosing namespace, but they do not introduce new names into that scope.
所以当你写的时候:
void t();
int main() {
int t(); // *
}
该内部声明引用封闭 namespace 的成员。所以这相当于写了:
void t();
int t();
int main() {}
但是函数不能仅仅在返回类型上重载,所以这段代码是病式的。 Clang 拒绝这两个程序,gcc 只拒绝后者。我相信这是一个 gcc 错误。
关于c++ - 使用其他类型的函数声明违反 C++ 中的类型安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36224099/