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

时间:2015-01-25 21:13:17

标签: c++ oop design-patterns destructor

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

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

每个类中的析构函数将删除使用new命令创建的任何数组。在我的代码中,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;
}

1 个答案:

答案 0 :(得分:1)

您传递了引用,但是您没有存储引用:

ECU ecu;

表示您的成员将是构造函数参数引用的对象的副本。

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

ECU& ecu;
相关问题