【发布时间】:2012-08-24 04:46:00
【问题描述】:
我正在编写一些代码来实现对象的深层副本。
这是我的代码:
//---------------------------------------------------------------------------
#pragma hdrstop
#include <tchar.h>
#include <string>
#include <iostream>
#include <sstream>
#include <conio.h>
using namespace std;
//---------------------------------------------------------------------------
class Wheel
{
public:
Wheel() : pressure(32)
{
ptrSize = new int(30);
}
Wheel(int s, int p) : pressure(p)
{
ptrSize = new int(s);
}
~Wheel()
{
delete ptrSize;
}
void pump(int amount)
{
pressure += amount;
}
int getSize()
{
return *ptrSize;
}
int getPressure()
{
return pressure;
}
private:
int *ptrSize;
int pressure;
};
class RacingCar
{
public:
RacingCar()
{
speed = 0;
*carWheels = new Wheel[4];
}
RacingCar(int s)
{
speed = s;
}
RacingCar(RacingCar &oldObject)
{
for ( int i = 0; i < sizeof(carWheels)/sizeof(carWheels[0]); ++i)
{
Wheel oldObjectWheel = oldObject.getWheel(i);
carWheels[i]=new Wheel(oldObjectWheel.getSize(),oldObjectWheel.getPressure());
}
}
void Accelerate()
{
speed = speed + 10;
}
Wheel getWheel(int id)
{
return *carWheels[id];
}
void printDetails()
{
cout << carWheels[0];
cout << carWheels[1];
cout << carWheels[2];
cout << carWheels[3];
}
private:
int speed;
Wheel *carWheels[4];
};
#pragma argsused
int _tmain(int argc, _TCHAR* argv[])
{
RacingCar testCar;
testCar.printDetails();
RacingCar newCar = testCar;
newCar.printDetails();
getch();
return 0;
}
//---------------------------------------------------------------------------
由于某种原因,我的 C++ 构建器在编译此代码后崩溃。上面是否有任何不正确的内容会导致崩溃。没有编译错误,程序只是崩溃了。
【问题讨论】:
-
使用调试器,因为在你这样做之前缺乏研究工作而被否决。
-
你为什么要在类中创建一个包含 4 个指针的数组,为构造函数中的第一个分配 4 个新的 Wheels,然后迭代最初的 4 个?如果您总是想要四个轮子,只需使用
std::array<Wheel, 4>。无需在任何地方进行动态分配。 -
您没有 Wheel 类的复制 c-tor 和赋值运算符,如果您使用指针,在大多数情况下这是不正确的。如果您使用 C++ 编写,为什么不使用 std::vector?
-
ptrSize看起来也是一个普通的int的主要候选人。