c++ - 构造函数名称前的关键字 struct

标签 c++ visual-c++

当我看到这段代码用 MS Visual C++ 编译成功时,我很惊讶。

struct foo {
    struct foo(int i): value(i) {}
    int value;
};

在如此奇怪的上下文中关键字 struct 是什么意思?

最佳答案

在大多数情况下,您可以使用精心设计的类型说明符 struct foo,或等同于class foo,而不仅仅是类名。这对于解决歧义很有用:

struct foo {};  // Declares a type
foo foo;        // Declares a variable with the same name

foo bar;        // Error: "foo" refers to the variable
struct foo bar; // OK: "foo" explicitly refers to the class type

但是,您不能在声明构造函数时使用这种形式,因此您的编译器会错误地接受该代码。构造函数声明规范(在 C++11 12.1/1 中)只允许类名本身,而不是详细的类型说明符。

一般来说,当 Visual C++ 编译各种奇怪的代码时,您不应该感到惊讶。它因其对该语言的非标准扩展而臭名昭著。

关于c++ - 构造函数名称前的关键字 struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17746012/

相关文章:

c++ - 当我期望 R 中的数据帧输出时,为什么 Rccp 返回类似列表的输出?

c++ - 具有关联属性的 boost::hash_combine 的替代方案?

visual-c++ - 如何从 Visual C++ 调用 jar 文件中的方法?

c++ - 存储设置的最佳实践

linux - 使用 gcc 查找要在项目中链接的 .o 文件顺序的任何工具

c++ - C++ 编译器如何合并相同的字符串文字

c++ - 使用 cURL 获取 HTTP xml 错误响应

c++ - ptr->ai_family 与 AF_INET 相比有何作用

c++ - QThread 和 QTcpSocket

c++ - C++ 中的数据成员偏移量