这是我的代码:
//---------------------------------------------------------------------------
#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)
{
ptrSize = new int(s);
pressure = p;
}
~Wheel()
{
delete ptrSize;
}
void pump(int amount)
{
pressure += amount;
}
private:
int *ptrSize;
int pressure;
};
class RacingCar
{
public:
RacingCar()
{
speed = 0;
Wheel carWheels = new Wheel[3];
}
RacingCar(int s)
{
speed = s;
}
void Accelerate()
{
speed = speed + 10;
}
private:
int speed;
};
我使用此代码创建一个 RacingCar 对象:
RacingCar test();
然而我收到以下错误:
[BCC32 错误] 问题 4.cpp(48): E2285 找不到匹配 'Wheel::Wheel(const Wheel&)'
在线:
Wheel carWheels = new Wheel[3];
我想创建一个由 4 个轮子组成的数组作为堆上的对象数组。
我究竟做错了什么?
更新
我想为 RacingCar 类使用复制构造函数,它将创建 RacingCar 对象的深层副本,然后编写代码来证明 RacingCar 对象的副本是深层副本。
我可以帮忙吗?
这是我的代码:
class RacingCar
{
public:
RacingCar()
{
speed = 0;
Wheel* carWheels = new Wheel[3];
}
RacingCar(int s)
{
speed = s;
}
RacingCar(const RacingCar &oldObject)
{
//I am not sure what to place here.
Wheel* carWheels = new Wheel[3];
}
void Accelerate()
{
speed = speed + 10;
}
private:
int speed;
};
* 第二次更新
这是我当前的代码:
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(const 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];
}
private:
int speed;
Wheel *carWheels[4];
};
复制构造函数无法正常工作。我在以下位置出现错误:
Wheel oldObjectWheel = oldObject.getWheel(i);
我究竟做错了什么?