c++ - 使用其他类型的函数声明违反 C++ 中的类型安全?

标签 c++ type-conversion type-safety

我是 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/

相关文章:

Objective-C 方法参数类型安全

java - 枚举、类、反射和泛型转换

c++ - 类型安全的 C++11 枚举类标志模板

c++ - Orwell Dev-C++ 中的 Unicode 字符串

c++ - 整数到字符串 : Without using stoi library

c# - 如何使用 TypeConverter 获取标志枚举以转换为 UInt64

arrays - 在 Go 中将固定大小的数组转换为可变大小的数组

c++ - 如何将 AnsiString 转换为 char?

c++ - 将双空格替换为单空格

c++ - 从函数返回 "int * const"