在 C++ 中,我想不出我想从一个继承私有/保护的情况基类:
In C++, I can't think of a case in which I would like to inherit private/protected from a base class:
class Base;
class Derived1 : private Base;
class Derived2 : protected Base;
真的有用吗?
当您想要访问基类的某些成员,但又不想在类接口中公开它们时,它很有用.私有继承也可以看作是某种组合:C++ faq-lite 给出下面的例子来说明这个语句
It is useful when you want to have access to some members of the base class, but without exposing them in your class interface. Private inheritance can also be seen as some kind of composition: the C++ faq-lite gives the following example to illustrate this statement
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
};
为了获得相同的语义,您也可以将汽车类编写如下:
To obtain the same semantic, you could also write the car Class as follow:
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
};
然而,这种做法有几个缺点:
However, this way of doing has several disadvantages:
这篇关于为什么我们在 C++ 中实际上需要 Private 或 Protected 继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!