使用 struct 关键字声明一个类,反之亦然
但当然,我知道我们不应该考虑做这样的事情,但这仍然很有趣:
class A; //declaration
struct A {...}; //definition
struct B; //declaration
class B {...}; //definition
当我思考它时,如果真的允许这样的事情,我看不出有任何问题(因为结构和类是本质上是同一件事)。但这是(标准方面)吗?
MSVC 接受并编译它,但会发出警告。
But of course we shouldn't even think of doing such things, I know, but still this is quite interesting:
class A; //declaration
struct A {...}; //definition
struct B; //declaration
class B {...}; //definition
When I think about it, I don't see any problems if such a thing were really allowed(because struct and class are essentially the same thing). But is it (standard-wise)?
MSVC accepts and compiles it, with a warning.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据标准,它是允许的,但正如一些编译器警告的那样,它不是很有用。
我相信该警告是由 MSVC 对结构和类使用不同的名称修饰引起的,这会使其变得更没用...
根据 @Armen 的请求:
7.1.5.3 详细的类型说明符,p3
It is allowed according to the standard, but as some compilers warn about it, it is not very useful.
I believe the warning is/was caused by MSVC using a different name mangling for structs and classes, which would make it even less useful...
On request from @Armen:
7.1.5.3 Elaborated type specifiers, p3
根据 C++03 标准 9.1 - 2
“类定义将类名引入到其定义的范围中,并隐藏任何类、对象、函数,或在封闭范围 (3.3) 中该名称的其他声明。”
因此,根据标准它是有效的。
玩一下示例代码:
这是输出:
C++ struct 和 struct 之间的唯一区别是: class 是结构的默认访问说明符是公共的,而类的默认访问说明符是私有的。
所以,从上面的例子来看:
在这种情况下,编译器将
A
视为结构
&B
作为class
如您所见,编译器遵循标准的引用,并且带有定义的类型是编译器通过声明类型识别的类型。
As per C++03 Standard 9.1 - 2
"A class definition introduces the class name into the scope where it is defined and hides any class, object, function, or other declaration of that name in an enclosing scope (3.3)."
So it is valid as per the standard.
Playing around a bit with the example code:
Here is the output:
The only difference between C++ struct & class is that default access specifier for structure is public while for class it is private.
So, From the above example:
In this case compiler treats
A
as astructure
&B
as aclass
As you see, the compiler follows the quote from the standard and the type with the definition is what the compiler recognizes, over the declaration type.