关于" 如何从基类公开继承,但在派生类中从基类私有化一些公共方法? "的问题,我有一个后续问题:
我可以理解,C++标准允许派生类放宽继承方法的访问限制,但我想不出任何合法的用例,在派生类中强加访问限制是有意义的.
根据我对继承概念的理解,如果Derived类是公共类Base,那么你可以用Derived完成任何你可以用Base做的事情.如果不希望Derived满足Base的接口,那么首先不应该使用(公共)继承.(事实上,当我在ROOT的TH2 :: Fill(双)中在野外遇到这种技术时,遗传滥用是一个明显的例子.)
对于虚拟方法,Derived中的访问限制也是无用的,因为Derived的任何用户都可以通过将Derived*强制转换为Base*来使用它们.
因此,从我有限的C++新手的角度来看,这些限制是误导性的(Derived的程序员可能会假设他的虚拟现在受保护的方法不被其他任何人调用,实际上可能是这样)并且也让我感到困惑公共继承应该意味着什么.
是否有一些我遗漏的合法用例?
来自本周大师赫伯·萨特#18 :
准则#3:仅当派生类需要调用虚函数的基实现时,才使虚函数受到保护。
有关详细答案,请阅读我在下面编写的代码中的评论:
#include <iostream>
#include <typeinfo>
#include <memory>
struct Ultimate_base {
    virtual ~Ultimate_base() {}
    void foo() { do_foo(); }
protected:
    // Make this method protected, so the derived class of this class
    // can invoke this implementation
    virtual void do_foo() { std::cout << "Ultimate_base::foo"; }
};
struct Our_derived : Ultimate_base {
private:
    // Make this method private, so the derived class of this class
    // can't  invoke this implementation
    void do_foo() {
        Ultimate_base::do_foo();
        std::cout << " Our_derived::foo";
    }
};
struct Derive_from_derive : Our_derived {
private:
    void do_foo() {
        // You can't call below code
        // vvvvvvvvvvvvvvvvvvvvvv
        // Our_derived::do_foo();
        std::cout << " Derive_from_derive::foo";
    }
};
// This class is marked final by making its destructor private
// of course, from C++11, you have new keyword final
struct Derive_with_private_dtor : Ultimate_base {
private:
    ~Derive_with_private_dtor() {}
};
// You can't have below class because its destructor needs to invoke
// its direct base class destructor
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
/* 
struct Derive_from_private_dtor : Derive_with_private_dtor {
};
*/
int main() {
    std::unique_ptr<Ultimate_base> p = std::make_unique<Our_derived>();
    p->foo();
    p = std::make_unique<Derive_from_derive>();
    p->foo();
    p.reset(new Derive_with_private_dtor);
}