[英]Access outer struct with the same name
Look at my sample code 看看我的示例代码
struct A
{
int member;
};
int main()
{
int A; //Line 1
A b; //Line 2
b.member = int(); //Line 3
}
Errors are 错误是
prog.cpp: In function ‘int main()’:
prog.cpp:9: error: expected `;' before ‘b’
prog.cpp:9: warning: statement has no effect
prog.cpp:10: error: ‘b’ was not declared in this scope
How to access structure A in second line ? 如何在第二行访问结构A? Why do I get the error anyway?
为什么我还是得到错误?
How to remove the error in Line 2?
如何删除第2行中的错误?
Use Elaborated Type Specifier, ie instead of writing A b;
使用Elaborated Type Specifier,即代替写
A b;
write struct A b;
写
struct A b;
. 。
3.4.4 Elaborated type specifiers
3.4.4详细说明的类型说明符
An elaborated-type-specifier may be used to refer to a previously declared class-name or enum-name even though the name has been hidden by a non-type declaration (3.3.7) .
精心设计的类型说明符可用于引用先前声明的类名或枚举名, 即使该名称已被非类型声明隐藏(3.3.7) 。 The class-name or enum-name in the elaborated-type-specifier may either be a simple identifer or be a qualified-id.
elaborated-type-specifier中的class-name或enum-name可以是简单的标识符,也可以是qualified-id。
Why do I get the error anyway?
为什么我还是得到错误?
Because A
outside main is hidden inside main after the definition of int A
. 因为
A
外主要被定义后内主要隐藏int A
。 The only way to access struct A
is by using elaborated-type-specifier. 访问
struct A
的唯一方法是使用elaborated-type-specifier。
3.3.7 Name hiding
3.3.7名称隐藏
2) A class name (9.1) or enumeration name (7.2) can be hidden by the name of an object, function, or enumerator declared in the same scope.
2)类名(9.1)或枚举名(7.2)可以通过在同一范围内声明的对象,函数或枚举器的名称隐藏。 If a class or enumeration name and an object, function, or enumerator are declared in the same scope (in any order) with the same name , the class or enumeration name is hidden wherever the object, function, or enumerator name is visible.
如果类或枚举名称以及对象,函数或枚举器在同一作用域(按任何顺序)中声明具有相同名称 ,则在对象,函数或枚举器名称可见的任何位置都会隐藏类或枚举名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.