重写方法时访问说明符
假设您有一个使用访问说明符 public 定义虚拟方法的类。 您可以更改重写方法上的访问说明符吗? 我假设不会。 寻找解释。
Assume you have a class that defines virtual methods with the access specifier public.
Can you change the access specifier on your overriden methods?
I am assuming no.
Looking for an explanation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
答案是:有点。您只能更改派生类有权访问的成员的访问权限。继承类型没有任何影响 - 这只控制继承成员的默认访问权限(在某种程度上,遵循其他规则)。
因此,您可以将基类的受保护成员设置为公共或私有;或基地的公共成员受保护或私有。但是,您不能将基地的私人成员设为公开或受保护。
示例:
上面的代码在 g++ 4.1.2 上引发以下错误:
main.C:7: error: 'void Foo::private_member()' is private
main.C:14: error: inside this context
另外,覆盖没有任何内容与更改方法的访问权限有关。您可以重写虚拟私有方法,只是不能从派生类调用它。
The answer is: sort of. You can only change the access of members the derived class has access to. The type of inheritance has no effect - this only controls the default access for inherited members (to a point, following other rules).
So, you can make a base class's protected members public or private; or a base's public members protected or private. You cannot, however, make a base's private members public or protected.
Example:
The above code elicits the following error on g++ 4.1.2:
main.C:7: error: 'void Foo::private_member()' is private
main.C:14: error: within this context
Additionally, overriding has nothing to do with changing the access of a method. You can override a virtual private method, you just cannot call it from a derived class.
是的,你可以,但它“不明白”。
看一下 在 C++ 中使用私有函数覆盖公共虚拟函数< /a>
Yes you can, but it "doesn't grok".
Take a look at Overriding public virtual functions with private functions in C++
你绝对可以。但这没有意义。如果它是公共继承,那么您始终可以将对象强制转换为其基类。如果是私有继承,则默认情况下所有基方法都已经是私有的。在受保护继承的情况下,您可以将基方法设为私有,这样就可以防止可能的派生类调用它,但我不太明白为什么可能需要它。
You definitely can. But it makes no sense. If it is a public inheritance, then you can always cast an object to its base. If it's a private inheritance, all base methods are already private by default. In case of protected inheritance you can make the base method private, so you prevent possible derived classes from calling it, but I don't really understand why one might need it.
是的,您可以,事实上您甚至不需要覆盖或使用虚拟任何东西。
如果它们也是虚拟的,则同样有效。或者,正如其他人指出的那样,虚函数查找会忽略实现类指定的访问;您可以转换为的任何类都可以在编译时提供访问权限。
另一方面,如果没有
D
中的特殊声明,ABC
的public
接口确实无法通过D
访问> 因为您无法向上转换为ABC
。如果woof
和moo
是virtual
,您可能希望将覆盖设置为private
以隐藏它们。也许这更好地回答了这个问题。Yes you can, and in fact you don't even need to override or use virtual anything.
The same works if they are virtual, too. Or, as others noted, virtual function lookup ignores the access specified by the implementing class; any class you can cast to may provide access at compile time.
On the other hand, without the special declarations in
D
, thepublic
interface ofABC
would indeed be inaccessible throughD
because you wouldn't be able to upcast toABC
. And ifwoof
andmoo
werevirtual
, you would want to make the overridesprivate
to hide them. Perhaps that better answers the question.