是否可以将具有相同名称的变量声明为不同的结构? 例如:
struct first
{
int a;
int b;
int the_same;
};
struct second
{
int x;
int y;
int the_same
};
答案 0 :(得分:3)
是的,它们运作良好,因为它们属于不同的code scopes。您可以first.the_same
和second.the_same
访问它们。
[...]范围是名称解析的重要组成部分,而这又是语言语义的基础。名称解析(包括范围)因编程语言而异,并且在编程语言中,因实体类型而异。与命名空间一起,范围规则在模块化编程中至关重要,因此程序的一部分的更改不会破坏不相关的部分。 [...]
答案 1 :(得分:1)
是的,您可以在不同的结构中使用具有相同名称的变量。
struct first
{
int a;
int b;
int the_same;
};
先听听a,b和the_same是结构的元素。并在结构中
struct second
{
int x;
int y;
int the_same
};
x,y和the_same是结构第二的元素。
编译器会将此变量与结构名称一起引用,而不是单独使用..
答案 2 :(得分:0)
有可能这样做。您可能认为它就像Enums,如果您在2个不同的枚举中有相同的值,您将得到编译时错误,但如果枚举命名空间不同则可能。例如:
namespace a {
enum a { a, b, c }
}
namespace b {
enum a {a, b, c}
}