Gal*_*man 58 c++ inheritance private protected c++-faq
在C++中,我想不出一个我希望从基类继承private/protected的情况:
class Base;
class Derived1 : private Base;
class Derived2 : protected Base;
Run Code Online (Sandbox Code Playgroud)
它真的有用吗?
Luc*_*lle 45
当您想要访问基类的某些成员但不在类接口中公开它们时,它非常有用.私有继承也可以看作是某种组合:C++ faq-lite给出了以下示例来说明这个语句
class Engine {
public:
Engine(int numCylinders);
void start(); // Starts this Engine
};
class Car {
public:
Car() : e_(8) { } // Initializes this Car with 8 cylinders
void start() { e_.start(); } // Start this Car by starting its Engine
private:
Engine e_; // Car has-a Engine
};
Run Code Online (Sandbox Code Playgroud)
要获得相同的语义,您还可以编写汽车类如下:
class Car : private Engine { // Car has-a Engine
public:
Car() : Engine(8) { } // Initializes this Car with 8 cylinders
using Engine::start; // Start this Car by starting its Engine
};
Run Code Online (Sandbox Code Playgroud)
但是,这种做法有几个缺点:
Joh*_*itb 40
私人在很多情况下都很有用.其中只有一个是政策:
另一个有用的场合是禁止复制和分配:
struct noncopyable {
private:
noncopyable(noncopyable const&);
noncopyable & operator=(noncopyable const&);
};
class my_noncopyable_type : noncopyable {
// ...
};
Run Code Online (Sandbox Code Playgroud)
因为我们不希望用户具有noncopyable*对象的类型指针,所以我们私下派生.这不仅适用于不可复制的,也适用于许多其他此类类(政策是最常见的).