基于成员的习惯用法有时需要受保护的继承。
惯用语解决的问题如下:有时需要使用派生类的成员初始化基类,例如
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)