private inheritance is a syntactic variant of composition (AKA aggregation and/or has-a).
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
};
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
};
到底什么时候使用私有继承,什么时候组合?
Use composition when you can, and use private inheritance when you have to.
我在MITK的源码里看到大量使用Private Inheritance。故有此疑问。