向动态数组中添加新对象

Adding new objects to dynamic array

本文关键字:对象 新对象 添加 动态 数组      更新时间:2023-10-16

我正在尝试编写函数来添加对象名称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语句的一部分。您的代码将在第一次迭代中仅return。你需要在这两行周围加上大括号。

当然,正如注释所说,您不应该自己这样做内存管理。使用std::vector代替。您的函数将变成只有几行。

您似乎没有对变量"hotels"进行任何声明。