基类重载方法的访问声明
假设我们在基类中重载了方法,并且派生类被继承为私有/受保护。
- 我们可以只恢复重载方法的一个/几个原始访问级别吗?
- 在 GCC 4.4.0 上,我尝试将基本方法置于受保护访问之下,然后使用私有访问继承它。当我尝试恢复公共访问级别时,它起作用了!这是它应该如何工作的吗?或者是编译器上的错误?据我了解,恢复访问级别不应用于提升或降级成员的访问级别。
代码片段:
class base {
public:
void method() {}
void method(int x) {}
protected:
void method2() {}
};
class derived : private base {
public:
base::method; // Here, i want to restore only the none parameterized method
base::method2; // method2 is now public??
};
Given that we have overloaded methods in base class, and a derived class that was inherited as private/protected.
- Can we restore only one/several of the original access level of the overloaded methods?
- On GCC 4.4.0 i try to put the base methods under protected access, then inherited it using private access. When i try to restore the access level to public, it works! Is this how its suppose to work? or is it a bug on the compiler? To my understanding, restoring access level shouldn't be able to be used to promote or demote a member's access level.
Code snippet :
class base {
public:
void method() {}
void method(int x) {}
protected:
void method2() {}
};
class derived : private base {
public:
base::method; // Here, i want to restore only the none parameterized method
base::method2; // method2 is now public??
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过
using
声明更改继承函数的可访问性无法在给定的重载上有选择地进行,原因很简单,using
声明仅引入一个名称 进入声明性区域,并且根据定义,函数重载共享相同的名称。我在这里看到的唯一替代方法是使用简单的转发函数:
我不太确定我是否理解您的第二个问题,但是是的:您可以通过
using
声明更改派生类中的基成员可访问性。Changing accessibility of inherited functions through a
using
declaration cannot be done selectively on given overload for the simple reason that ausing
declaration only introduces a name into the declarative region and that by definition, functions overloads share the same name.The only alternative I see here is to use trivial forwarding functions :
I'm not quite sure I understand your second question, but yes : you can change base members accessibility in a derived class through
using
declarations.您本身不恢复访问权限。您设置访问权限。正如您在上面所做的那样,您可以显式设置任何方法的访问权限,包括之前声明为
private
的方法。You don't restore access, per se. You set access. As you are doing above, you can explicitly set the access for any method, including ones previously declared as
private
.如果派生类希望如此,则不可能阻止受保护的方法公开,因为您只需编写一个较小的包装器即可完成。
private
是另一回事。It would be impossible to prevent protected methods from being public if the derived class wanted it so, as you could just write a minor wrapper and done.
private
is another matter.