gpt4 book ai didi

c++ - 访问同名的外部结构

转载 作者:太空狗 更新时间:2023-10-29 20:48:02 26 4
gpt4 key购买 nike

看我的示例代码

struct A
{
int member;
};

int main()
{
int A; //Line 1
A b; //Line 2
b.member = int(); //Line 3
}

错误是

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

如何在第二行访问结构 A?为什么我还是会收到错误消息?

最佳答案

How to remove the error in Line 2?

使用 Elaborated Type Specifier,即不是写 A b; 而是写 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?

因为 int A 定义后,main 外部的 A 隐藏在 main 内部。访问 struct A 的唯一方法是使用 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.

关于c++ - 访问同名的外部结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4163799/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com