我正在尝试编写函数以将对象名称 Hotel 添加到动态分配的数组中。问题是,虽然我的代码可以添加第一个,但它无法添加任何其他内容。这是负责添加新对象的代码。
void HotelReservationSystem::addHotel( const std::string name, const int numFloors, const int *numRooms)
{
if ( hotelNum == 0 && hotels == NULL){
hotels = new Hotel[1];
Hotel hotelA ( name, numFloors, numRooms);
hotels[0] = hotelA;
hotelNum++;
std::cout << "Hotel " << name << " is added." << std::endl;
return;
}
for (int x = 0; x < hotelNum; x++){
if ( name == hotels[x].getName())
std::cout << "\n" << "Hotel " << name << " already exists." << std::endl;
return;
}
Hotel* temp = new Hotel[hotelNum+1];
for ( int x = 0; x < hotelNum; x++){
temp[x] = hotels[x];
}
temp[hotelNum] = Hotel ( name, numFloors, numRooms);
delete [] hotels;
hotels = temp;
hotelNum++;
std::cout << "Hotel " << name << " is added." << std::endl;
}
到目前为止,我无法检测到此代码有任何问题。
最佳答案
for (int x = 0; x < hotelNum; x++){
if ( name == hotels[x].getName())
std::cout << "\n" << "Hotel " << name << " already exists." << std::endl;
return;
}
这里,return
不是if
语句的一部分。您的代码只会在第一次迭代中返回
。您需要用大括号括起这两行。
当然,正如评论所说,你不应该自己做这样的内存管理。请改用 std::vector
。您的功能将变得只有几行。
关于c++ - 将新对象添加到动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24659527/