当我看到这段代码用 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/