C++:简单的任务,析构函数被多次调用
C++: simple quest., destructors being called multiple times
我正在学习如何用c ++做OOP。请看一下我的简单示例,并告诉我我的 OOP 方法是否不正确。
我希望这样做:创建一个"settings"类型类,该类将通过引用传递到其他几个类中。在示例中,这是"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;
}
您正在传递引用,但未存储引用:
ECU ecu;
表示您的成员将是构造函数参数引用的对象的副本。
如果要存储引用,请存储引用:
ECU& ecu;
相关文章:
- 什么时候调用析构函数
- C++-明确何时以及如何调用析构函数
- C++ 防止在映射中放置()时调用析构函数
- 调用析构函数以释放动态分配的内存
- C++:使用方法调用析构函数的顺序是什么?
- 向量推回调用析构函数时调用析构函数
- 如何在调用析构函数时优雅地停止/销毁带有阻塞调用C++线程?
- C++,我应该调用析构函数吗?
- 如何获取有关在 Clang LibTooling 中调用析构函数的信息?
- 当我从 std::vector 中的新放置调用析构函数时会发生什么?
- 为什么这里不调用析构函数
- 在调用 std::bind 的产品后意外调用析构函数
- 为什么在传递给函数而不是构造函数时调用析构函数?
- 如何在C++中调用析构函数
- 为什么为未删除的对象调用析构函数?
- 调用析构函数时出错
- C++ 在不释放内存的情况下调用析构函数
- 为什么在运算符删除中不调用析构函数?
- C++ 调用析构函数后动态模板队列"double free or corruption (out)"
- 在 postOrderDelete 上调用析构函数时引发的异常