C++:简单的任务,多次调用析构函数

标签 c++ oop design-patterns destructor

我正在学习如何使用 C++ 进行 OOP。请看看我的简单示例,并告诉我我的 OOP 方法是否不正确。

我希望这样做:创建一个“设置”类型的类,该类将通过引用传递给其他几个类。在示例中,这是“ECU”类。我正在使用成员初始化将 ECU 类传递给每个类。这是正确的方法吗?

每个类中的析构函数将删除使用新命令创建的任何数组。在我的代码中,ECU 的析构函数被多次调用。如果我在 ECU 中有一个“myArray”,并且在 ECU 析构函数中使用“delete[] myArray”,我会得到错误。执行此操作的正确方法是什么?

此外,传输和引擎的析构函数在程序退出之前被调用。这是因为编译器知道它们不会被再次使用吗?

// class_test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;


class ECU
{
public:
    ECU()
    {
        cout << "ECU Constructor" << endl;  
    }
    ~ECU()
    {
        cout << "ECU Destructor" << endl;
    }

    void flash()
    {
        softwareVersion = 12;
    }

    int pullCode()
    {
        return softwareVersion;
    }

private:
    int softwareVersion;
};

class Engine 
{
public:
    Engine(ECU &e) : ecu(e) 
    {
        horsepower = 76;
        cout << "Engine Constructor" << endl;   
    }
    ~Engine()
    {
        cout << "Engine Destructor" << endl;
    }

private:
    ECU ecu;
    int horsepower;
};

class Transmission
{
public:
    Transmission(ECU &e) : ecu(e) 
    {
        cout << "Transmission Constructor" << endl;
        gearRatios = new double[6];
        if (ecu.pullCode() == 12){
            for (int i = 0; i < 6; i++)
                gearRatios[i] = i+1.025;
            cout << "gear ratios set to v12.0" << endl;
        }
    }
    ~Transmission()
    {
        delete[] gearRatios;
        cout << "Transmission Destructor" << endl;
    }

private:
    ECU ecu;
    double *gearRatios;
};

class Car 
{
public:
    Car(ECU &e) : ecu(e) 
    {
        cout << "Car Constructor" << endl;

        Engine myEngine(ecu);
        Transmission myTrans(ecu);
    }
    ~Car()
    {
        cout << "Car Destructor" << endl;
    }

private:
    ECU ecu;
};

int _tmain(int argc, _TCHAR* argv[])
{
    ECU myComputer;
    myComputer.flash();
    Car myCar(myComputer);
    system("pause");
    return 0;
}

最佳答案

你正在传递一个引用,但你没有存储一个引用:

ECU ecu;

意味着您的成员将是构造函数参数引用的对象的拷贝。

如果要存储引用,请存储引用:

ECU& ecu;

关于C++:简单的任务,多次调用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28141593/

相关文章:

c++ - MingW C++ 文档?

c++ - 仅接收7位读取串行端口Midi字节C++

php - 在静态函数中访问公共(public)/私有(private)函数?

javascript - JS 模式提供函数名称作为字符串

c++ - 为什么 Visual Studio 2010 调试器看不到静态 const 类成员?

c++ - 按钮 onClick 的工作原理

design-patterns - 命令模式的uml图

java - 如何防止具体类的实例化?

Java:对象的初始化顺序

Python - 访问类的 protected 成员_