c++ - 替代基本析构函数上的虚函数调用

标签 c++ oop design-patterns

所以,我写了下面的代码。

#include <iostream>

class AbstractMachine
{
public:
    void powerOn();
    void powerOff();
    bool isPoweredOn();

    virtual ~AbstractMachine();

protected:
    virtual void powerOnImpl() = 0;
    virtual void powerOffImpl() = 0;

private:
    bool m_isPoweredOn;
};

bool AbstractMachine::isPoweredOn()
{
    return m_isPoweredOn;
}

void AbstractMachine::powerOn()
{
    if (!m_isPoweredOn)
    {
        powerOnImpl();
        m_isPoweredOn = true;
    }
}

void AbstractMachine::powerOff()
{
    if (m_isPoweredOn)
    {
        powerOffImpl();
        m_isPoweredOn = false;
    }
}

AbstractMachine::~AbstractMachine()
{
    powerOff();       // (1)
    std::cout << "Destroying a machine" << std::endl;
}

class AirConditioner : public AbstractMachine
{
protected:
    void powerOnImpl() override;
    void powerOffImpl() override;
public:
    ~AirConditioner();
};

void AirConditioner::powerOnImpl()
{
    std::cout << "Turning on air conditioner" << std::endl;
}

void AirConditioner::powerOffImpl()
{
    std::cout << "Turning off air conditioner" << std::endl;
}

AirConditioner::~AirConditioner()
{
    //powerOff();        // (2)
    std::cout << "Destroing air conditioner" << std::endl;
}


int main()
{
    AbstractMachine *machine = new AirConditioner();
    machine->powerOn();
    delete machine;
}

这将失败,因为当基本析构函数调用 (1) 上的派生函数时,派生对象已经被销毁。

当我评论 (1) 和取消评论 (2) 时,这运行良好,但我想在这里做的是自动并始终在机器被破坏之前关闭机器,尽管“关闭电源”操作取决于在定制机器上

有更好的方法吗? 我应该放弃吗? 或者它甚至不是 OOP 设计的正确方法?

最佳答案

如您所见,当基类构造函数运行时,派生类部分不再存在。没有什么技巧可以做到这一点,所以没有办法在基本析构函数中(或从)基本析构函数中完成所有操作。

你只需要弄清楚关闭的哪一部分属于每个级别,并让每个析构函数处理它自己的级别。当对象被销毁时,每个级别的析构函数都会运行,从下到上,所以一切都完成了。我认为这就是 OOP 方法。

关于c++ - 替代基本析构函数上的虚函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48088029/

相关文章:

php - 组织类(class) - 帮助 OOP 初学者

javascript - 在网页上同时使用 JSP 和 Javascript 的设计模式

java - 如何在线程之间进行健康检查?

c++ - 识别模板中的值是 bool

c++ - 如何解决 numeric_limits<T>::min() 的不一致定义?

javascript - Javascript 自执行匿名函数的唯一实例

c++ - 这个简单的 Message 类是否证明使用智能指针是合理的?

c# - 动态条件逻辑

c++ - 在 C++ 中使用二维 vector 时出错

c++ - 构建 ACE_SSL