这篇文章的作者指出
“通常你不想访问太多其他类的内部,而私有继承为你提供了一些额外的权力(和责任)。但私有继承并不邪恶;它只是维护成本更高,因为它增加了有人更改会破坏您的代码的东西的可能性。”
Car
假设从 private 继承的以下代码Engine
:
#include <iostream>
using namespace std;
class Engine
{
int numCylinders;
public:
class exception{};
Engine(int i) { if( i < 4 ) throw exception(); numCylinders = i; }
void start() { cout << "Engine started " << numCylinders << " cylinders" << endl; }
};
class Car : private Engine
{
public:
Car(int i) : Engine(i) {}
using Engine::start;
};
int main()
{
try
{
Car c(4);
c.start();
}
catch( Engine::exception& )
{
cout << "A Car cannot have less than 4 cylinders" << endl;
}
}
我的问题是:如何Car
通过设置例如Engine
少于 4 个圆柱体、使用私有继承并且在基类中没有受保护成员来破坏此代码?