c++ - 与组合相比,为什么私有(private)继承会增加有人破坏我的代码的可能性?

标签 c++ private-inheritance

作者article指出

“通常你不想访问太多其他类的内部,私有(private)继承给了你一些额外的权力(和责任)。但私有(private)继承并不是邪恶的;它只是代价更高维护,因为它增加了有人更改会破坏您的代码的可能性。”

假设以下代码,其中 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 个汽缸、使用私有(private)继承且没有 protected 来破解此代码基类中的成员?

最佳答案

我认为问题不在于 Car 可以破解您的 Engine 代码,而是通过更改 Engine,有人可以破解您的 Car 代码。继承表示比组合更紧密的耦合,因此 Engine 中的更改更有可能破坏从它继承而不是包含它的类。在 C++ 的情况下,通过让 Car 包含一个 Engine 指针或智能指针来实现更松散的耦合。

关于c++ - 与组合相比,为什么私有(private)继承会增加有人破坏我的代码的可能性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9199113/

相关文章:

c++ - try..catch cython 中等效的宏包装器

c++ - "The C++ Programming Language"中描述的私有(private)继承用法

c++ - 用私有(private)基函数覆盖公共(public)虚函数?

c++ - 私有(private)继承 : name lookup error

c++ - 潜在溢出比较排序和各种排序算法的比较

c# - 在 C# 中使用具有另一个 C++ 类对象的 C++ 类

c++ - move map 的构造函数

c++ - private继承的直接基类阻止派生类定义间接基类的对象

编译器可以删除 C++(虚拟)私有(private)基类吗?

使用 cmake 和 pybind11 构建示例应用程序时找不到 Python.h