构造函数名称前的关键字结构

Fel*_*kov 9 c++ visual-c++

当我看到使用MS Visual C++编译的代码成功时,我感到很惊讶.

struct foo {
    struct foo(int i): value(i) {}
    int value;
};
Run Code Online (Sandbox Code Playgroud)

struct在这种奇怪的环境中,关键字是什

Mik*_*our 10

在大多数情况下,您可以使用详细说明的类型说明符 struct foo,或者等效地class foo使用类名称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
Run Code Online (Sandbox Code Playgroud)

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

一般来说,当Visual C++编译各种不稳定的代码时,你不应该感到惊讶.它因语言的非标准扩展而臭名昭着.

  • @ IanM_Matrix1:这是在类定义中使用`class`和`struct`之间的区别; 但是我们这里不讨论类定义,只是用于引用类类型的类型说明符.那里使用`class`和`struct`没有区别. (5认同)