c++ - 将新对象添加到动态数组

标签 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;
}

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

最佳答案

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/

相关文章:

javascript - 将属性添加到对象文字并返回

java - 如何达到扩展类的功能?

javascript - 如何打印数组中变量的名称?

c++ - 在我的主类中使用动态数组时出错

c++ - 为什么抛出局部变量调用 moves 构造函数?

c++ - SONAR——C代码分析

c++ - 什么时候应该在模板函数中使用 typename?

c++ - boost.Asio 在幕后执行什么处理程序?

c++ - 在 C++ 中创建一个以 6 为基数的大型数组?

c++ - C++ 中两个 vector 之间的元素交换