创建一个具有相同名称的结构和类 [英] Creating a struct and a class with the same name
问题描述
摘要:如果您用 struct
和类
详细:我正在查看一些代码,看到这样的警告:
警告:struct'foo'以前声明为类
当使用clang编译时,还有一些地方clang添加了注释:
foo.h:29:1:note:这里是你的意思吗?
class foo;
^ ~~~~
struct
显然这不是一个好的编码实践有一个结构和一个同名的类。看起来发生了什么事是开发人员正在编写自己的类,并使用了一个已经在他包含的另一个文件中使用的名称,并且他没有注意到。
但是,我的问题是编译器能够告诉被声明为 class foo
的变量和 struct foo之间的区别
:
发生的是开发者使用他创建的类栏
中的 class foo
我认为在此期间,声明 class foo
的位置已更改为 struct bar
。这就是为什么代码是编译。所以我想我的问题的答案是, struct
和 class
在声明对象时是可以互换的。 关键字 struct
和 class
在很大程度上是可以互换的。
即使你写 struct Foo
,你也创建了一个类类型
,名称为 Foo
。并且该名称在其
范围内必须是唯一的(出于C兼容性的原因有一个特殊的例外,但是最好忽略它)。
Summary: What happens if you declare a struct
and a class
with the same name.
Details:
I'm reviewing some code and I saw a warning like this:
warning: struct 'foo' was previously declared as a class
When compiling with clang there were also a couple of places where clang added notes saying:
foo.h:29:1: note: did you mean struct here?
class foo;
^~~~~
struct
Obviously this is not a good coding practice to have a struct and a class with the same name. It looks like what happened is the developer was writing his own class and used a name that was already in use in another file that he was including and he did not notice that.
However, my question is will the compiler be able to tell the difference between the variables that were declared as class foo
and the ones that were struct foo
?
Edit:
Actually what was happening was that the developer was using the class foo
in a class bar
that he had created. I think that in the meantime the place where the class foo
was declared had been changed to a struct bar
. So that was why the code was compiling. So I guess the answer to my question is that struct
and class
are interchangeable when declaring objects. Still I guess it's a good idea to use them consistently.
The keywords struct
and class
are largely interchangeable.
Even if you write struct Foo
, you have created a class type
with the name of Foo
. And that name must be unique within its
scope (with a special exception for reasons of C compatibility,
but which it is better to ignore).
这篇关于创建一个具有相同名称的结构和类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!