防止派生类从基础中隐藏非虚函数 [英] Prevent derived classes from hiding non virtual functions from base

查看:166
本文介绍了防止派生类从基础中隐藏非虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑我有A& B,以便

  class A 
{
public:
void Fun
};

B类:public A
{
....
};

我作为A类的设计器有什么办法可以强制执行派生类B和其他类从A派生,被阻止(获得某种错误)从隐藏非虚函数Fun()?

解决方案

如果您希望非 - virtual 成员函数始终以某种方式访问​​,然后简单地将其包装在命名空间范围自由函数中:

 命名空间显示{
void foo A& o){o.foo(); }
}

现在,B类客户可以随时进行

  void bar()
{
B o;
revealed :: foo(o);但是,无论B类引入了多少隐藏重载,客户端也可以只是一个简单的方法。 do

  void bar2()
{
B o;
A& ah = o;
ah.foo();
}

,他们可以执行

  void bar3()
{
B o;
o.A :: foo();
}

所以只是一个更容易理解的符号和意图



也就是说,没有可能,因为评论会有它,可用性是你默认的…


Consider that I have classes A & B such that

class A
{
   public:
   void Fun();
};

class B  : public A
{
   ....
};

Is there any way that I as a designer of class A can enforce that derived class B and other classes which derive from A, are prevented(get a some kind of error) from hiding the non virtual function Fun()?

解决方案

If you want the non-virtual member function to always be accessible in some way, then simply wrap it in a namespace scope free function:

namespace revealed {
    void foo( A& o ) { o.foo(); }
}

now clients of class B can always do

void bar()
{
    B o;
    revealed::foo( o );
}

However, no matter how much class B introduces hiding overloads, clients can also just do

void bar2()
{
    B o;
    A& ah = o;
    ah.foo();
}

and they can do

void bar3()
{
    B o;
    o.A::foo();
}

so just about all that's gained is an easier-to-understand notation and intent communication.

I.e., far from being impossible, as the comments would have it, the availability is what you have by default…

这篇关于防止派生类从基础中隐藏非虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆