在c ++中限制对纯虚函数的派生类的访问

Chr*_*ris 4 c++ virtual

class A
{    
public:
    void virtual magic() = 0;
    void bar()
    {
        magic();    // this should be legal
    }        
};

class B: public A
{    
public:
    void magic()
    {
        cout<<"implement magic here"<<endl;
    }
};

class C: public B
{
     void foo()
     {
         magic();     // this should not be allowed, i.e. create compile-time error
     }
};
Run Code Online (Sandbox Code Playgroud)

因此,该纯虚基类AB应访问magic(),但不排除任何派生类CB.这可以使用访问说明符和/或朋友声明或以任何其他方式实现吗?

NPE*_*NPE 7

基本上,您无法降低虚拟方法的可见性.一旦它被公开A,在任何派生类中都没有任何整洁的方式使它受到保护或私有.