C++继承:成员的范围和可见性
你能解释一下为什么这是不允许的,
#include <stdio.h>
class B {
private:
int a;
public:
int a;
};
int main() {
return 0;
}
而这是允许的吗?
#include <stdio.h>
class A {
public:
int a;
};
class B : public A{
private:
int a;
};
int main() {
return 0;
}
在这两种情况下,class B
中都有一个名为 a
的公共变量和一个私有变量。
现在编辑!
Can you explain why this is not allowed,
#include <stdio.h>
class B {
private:
int a;
public:
int a;
};
int main() {
return 0;
}
while this is?
#include <stdio.h>
class A {
public:
int a;
};
class B : public A{
private:
int a;
};
int main() {
return 0;
}
In both the cases, we have one public and one private variable named a
in class B
.
edited now!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,那不是真的。
在第一种情况下,同一范围内不能有两个同名的标识符。而在第二种情况下,
B::a
隐藏A::a
,并且要访问A::a
,您必须完全限定姓名:No, thats not true.
In the first case, you can't have two identifiers with the same name in the same scope. While in the second case,
B::a
hidesA::a
, and to accessA::a
you have to fully qualify the name:因为在第二个示例中,
B::a
隐藏了A::a
。您仍然可以访问它,但是编译器需要显式限定才能确定您正在请求具有相同hame的父类成员。在第一个示例中,两个
a
位于同一范围内,而在第二个示例中,范围不同。Because
B::a
hidesA::a
in the second example. You can still access it, but it needs explicit qualification for the compiler to figure out you are asking for the member of parent class with the same hame.In the first example both
a
's are in the same scope, while in the second example the scopes are different.第一个示例中的类 B 无效,因为 C++ 无法通过访问说明符(公共/私有/受保护)来区分成员。然而,命名空间是 C++ 区分成员的一种方式。在第二段代码的 B 类中,没有“public a”和“private a”,而是有
B::a
和A::a
。即使允许使用不同的访问说明符声明相同名称/签名的成员,也无法寻址正确的成员。
Class B in the first example is not valid because C++ cannot distinguish members by their access specifiers (public/private/protected). However, namespaces are a way for C++ to distinguish members. In class B in the second code you don't have a "public a" and a "private a", you have
B::a
andA::a
.Even if declaring members of the same name/signature with different access specifiers was allowed, there would be no way to address the correct member.
第一个是不允许的,因为它会导致定义不明确。在第二个中,虽然您确实有一个公共和一个私有
a
整数变量,但您已将 A::a 隐藏在 B 类中。编译器隐式地知道你想要什么,因为有一种方法可以显式访问隐藏变量。我还认为,这可以归结为名称修改:存储说明符最终不会成为实际名称的一部分。不过,我在这一点上可能是错的。
说明为什么允许一个变量而不允许另一个变量的最简单方法是查看编译器如何编译使用每个变量的成员函数。
在你的班级 b 中:
对于第二个例子:
The first isn't allowed because it leads to ambiguous definitions. In the 2nd, although you do have both a public and a private
a
integer variable, you've hidden A::a inside your B class. The compiler knows implicitly what you want because there is a way to explicitly access a hidden variables.I also believe that it boils down to name mangaling: storage specifiers don't end up as part of the actual name. I could be wrong on this however.
The easiest way to illustrate why one is allowed and why the other isn't is to look at how the compiler would compile a member function that uses each variable.
Inside your class b:
For the 2nd example: