问题
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()?
回答1:
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…
来源:https://stackoverflow.com/questions/14997210/prevent-derived-classes-from-hiding-non-virtual-functions-from-base