向动态数组中添加新对象
Adding new objects to dynamic array
我正在尝试编写函数来添加对象名称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"进行任何声明。
相关文章:
- 当一个新对象被分配到它的地址时,对象是否必须被销毁
- C++ 如何在将新对象分配给另一个对象时创建新对象
- 重用对象与创建新对象
- C++,创建新对象时类的对象更改
- 运算符重载 += 添加新对象
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 从使用概念定义的函数返回新对象
- 从 Rcpp 函数返回指向"新"对象的指针的正确方法
- 如何删除派生类中基类对象的新对象
- 有没有一种方法可以从函数中返回一个新对象或对现有对象的引用
- 为模板参数类型中的新对象分配内存
- 删除通过取消引用新对象初始化的对象
- C++ 实例化新对象时不接受继承方法默认参数值
- 有没有办法删除传递给函数"foo(新对象())"的对象?
- 将 Eigen::MatrixXd 转换为 arma::mat 并在新对象上制作副本
- 创建新对象并立即为其设置属性时出现编译器错误
- 如何异步销毁对象并立即分配一个新对象
- 删除传递给 C++ 中成员函数的新对象
- 具有构造函数的新对象数组,需要在C++中设置参数
- 我可以制作一个对象方法,如果单独调用,它将自行修改,但如果在复制初始化期间调用,则会返回一个新对象?