【发布时间】:2012-02-08 18:17:21
【问题描述】:
article 的作者指出
“通常你不想访问太多其他类的内部,而私有继承给了你一些额外的权力(和责任)。但是私有继承并不邪恶;它只是更昂贵维护,因为它增加了某人更改某些内容会破坏您的代码的可能性。”
假设以下代码 Car 私下继承自 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 个柱面、使用私有继承且在基类中没有受保护成员来破解此代码?
【问题讨论】:
-
这是真的(根据某些真实的定义),但表达得不好。更紧密耦合的代码更难维护。