【问题标题】:C++: simple quest., destructors being called multiple timesC++:简单的任务,多次调用析构函数
【发布时间】:2015-03-24 08:42:12
【问题描述】:

我正在学习如何在 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;
}

【问题讨论】:

    标签: c++ oop design-patterns destructor


    【解决方案1】:

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

    ECU ecu;
    

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

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

    ECU& ecu;
    

    【讨论】:

    • 使用引用作为类成员存在一些问题,see here。例如,它使对象无法很好地进行复制分配或移动分配。 (这可能仍然是最好的解决方案;只是说会出现设计复杂性)。
    猜你喜欢
    • 2012-07-12
    • 2018-12-04
    • 2018-02-03
    • 2012-01-13
    • 2014-08-22
    • 2018-12-19
    • 2014-05-18
    • 2021-07-03
    • 1970-01-01
    相关资源
    最近更新 更多