将新对象添加到动态数组中

时间:2014-07-09 16:53:04

标签: c++ object dynamic-arrays

我正在尝试编写函数来添加对象名称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;
}

到目前为止,我无法检测到此代码有任何问题。

2 个答案:

答案 0 :(得分:3)

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。你的功能只会变成几行。

答案 1 :(得分:0)

您似乎没有任何声明变量“酒店”。

相关问题