在哪些情况下我们需要保护继承?

gun*_*ter 6 c++ inheritance

公共和私人继承是明确的,但受保护的是什么?我们真正需要使用它的任何例子都能给我们带来好处吗?

Ale*_* C. 3

基于成员的习惯用法有时需要受保护的继承。

惯用语解决的问题如下:有时需要使用派生类的成员初始化基类,例如

struct foo
{
    virtual ~foo() {}

protected:
    foo(std::ostream& os)
    {
        os << "Hello !\n";
    }
};

struct bar : foo
{
    bar(const char* filename)
      : foo(file), file(filename) // Bad, file is used uninitialized
    {}

private:
    std::fstream file;
};
Run Code Online (Sandbox Code Playgroud)

但是在 后file构造的,因此传递给 的是无效的。 fooostreamfoo::foo

您可以使用辅助类和私有继承来解决这个问题:

struct bar_base
{
    std::fstream file;

protected:
    bar_base(const char* filename) 
      : file(filename) 
    {}   

    ~bar_base() {}
};

struct bar : private bar_base, public foo
{
    bar(const char* filename)
      : bar_base(filename), foo(file)
    {}
};
Run Code Online (Sandbox Code Playgroud)

Nowbar_base是在 之前构造的foo,并且ostream传递给的foo::foo是有效的。

如果你想file成为 的受保护成员bar,则必须使用受保护继承:

struct bar : protected bar_base, public foo { ... }
Run Code Online (Sandbox Code Playgroud)