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 ? Why do I get the error anyway?
How to remove the error in Line 2?
Use Elaborated Type Specifier, ie instead of writing A b;
write struct A b;
.
3.4.4 Elaborated type specifiers
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) . The class-name or enum-name in the elaborated-type-specifier may either be a simple identifer or be a qualified-id.
Why do I get the error anyway?
Because A
outside main is hidden inside main after the definition of int A
. The only way to access struct A
is by using elaborated-type-specifier.
3.3.7 Name hiding
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.