简而言之,我有一个C ++程序,它包含一个带有子类SportsCar和SUV的Car类,以及一个存储Car对象的CarInventory。
答案 0 :(得分:1)
你分配了10辆汽车的阵列。但是你只用4辆汽车初始化它。
因此,当displayVehichles
中的循环绕过访问carArray[5]
时,它可能会访问未初始化的内存。
这句话似乎很麻烦:
carArray = new Car *[maxStock];
应该是:
carArray = new Car *[maxStock];
for (int i = 0; i < maxStock; i++)
{
carArray[i] = NULL;
}
totalNumCars = 0;
这样,您的插入方法将正常运行。但是你的插入方法可以简单得多:
void CarInventory::insert(Car *car) {
if (totalNumCars < maxStock)
carArray[totalNumCars] = car;
totalNumCars++;
}
}
此外,虽然你可以按照它的方式确定已经宣布的汽车超出范围,但在你的CarInventory超出范围之前,它将引用已被删除的汽车对象。
使用std :: vector来保存你的汽车:
class CarInventory
{
std::vector<Car*> _cars;
public:
void displayVehicles()
{
for (auto i = _cars.begin(); i != _cars.end(); i++)
{
i->printInfo();
}
}
void insert(Car* car)
{
_cars.push_back(car);
}
};
现在仍然没有解决CarInventory类保留堆栈对象指针的问题。
这更好:
class CarInventory
{
std::vector<std::shared_ptr<Car>> _cars;
public:
void displayVehicles()
{
for (auto i = _cars.begin(); i != _cars.end(); i++)
{
i->printInfo();
}
}
void insert(std::shared_ptr<Car>& spCar)
{
_cars.push_back(spCar);
}
};
然后你的代码使用该类:
std::shared_ptr<Car*> createCar(const char* vin, const char* make, const char* color, int year)
{
Car* car = new Car(vin, make, color, year);
return std::shared_ptr<Car>(car);
}
int main(int argn, char *argv[])
{
CarInventory cars;
std::shared_ptr<Car*> toyota = createCar("2GCGC34M9F1152828", "Toyota", "Camry", "Green", 2012);
std::shared_ptr<Car*> honda = createCar("1C4BJWAG4DL602733", "Honda", "Civic", "Blue", 2015);
...
CarInventory cars;
cars.insert(toyota);
cars.insert(honda);
cout << "\n";
cars.displayVehicles();
}
答案 1 :(得分:1)
我认为问题在于插入功能
void CarInventory::insert(Car *car) {
for (int i = 0; i < inventorySize; i++) {
if (carArray[i]) {
i++;
}
如果您在carArray
中找到已加入i
的汽车,则会在for循环中再次递增i
。这样你就会跳过数组中的每个其他位置,它们将保持未初始化状态。