c++ - 使用常量变量声明对象数组

标签 c++ arrays pointers object

我有一个带有以下头文件的表对象:

#ifndef TABLE_H
#define TABLE_H
#include "Order.h"
#include "Waiter.h"

//                    0       1        2       3
enum TableStatus { IDLE, SEATED, ORDERED, SERVED };

class Waiter; // to take care of circular reference.

class Table 
{
private:
    int tableId;        // table number
    const int maxSeats; // table seat capacity
    TableStatus status; // current status, you can use assign like
                // status = IDLE;
    int numPeople;      // number of people in current party
    Order *order;       // current party's order
    Waiter *waiter;     // pointer to waiter for this table

public:
    Table(int tblid =0, int mseats = 0);    // initialization, IDLE
    void assignWaiter(Waiter *person);  // initially no waiter
    void partySeated(int npeople);      // process IDLE --> SEATED
    void partyOrdered(Order *order);    // process SEATED --> ORDERED
    void partyServed(void);         // process ORDERED --> SERVED
    void partyCheckout(void);       // process SERVED --> IDLE
    int getMaxSeats(void);
    int getStatus(void);
};
#endif

在我的主函数中,我需要声明一个表数组。但是,当我写 Table *table = new Table[10] 时,数组的每个元素都调用构造函数中的默认参数,并且每个表都以 0 的常量最大座位值结束。我需要能够单独调用它们的每个构造函数以具有不同的 maxSeats 值。

到目前为止,我能想出的唯一解决方案是声明一个指向表对象的指针数组,然后分别实例化每个指针。这部分有效,但上面代码中提到的 Waiter 类接受一个表数组作为参数,如果它传递了一个表指针数组,它将不起作用。

我可以执行什么过程来最终得到一个 Table 对象数组,这些对象的 maxSeats 常量变量具有不同的值?

还有一点需要说明:数组必须动态创建,所以我不能只显式调用 10 次或多次调用构造函数。我事先不知道数组必须有多大。

最佳答案

一种选择是使用 placement new :

Table* tables = static_cast<Table*>(new char[sizeof(Table) * count]);
for(int i = 0; i < count; i++) new(&tables[i]) Table(tblid[i], mseats[i]);

关于c++ - 使用常量变量声明对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24728285/

相关文章:

c - 使用指向常量数据的指针的替代方法?

c++ - 这个 nm 输出 "V typeinfo name for void*"是什么意思?

c++ - 开发 ActiveX 控件

c++ - 用更大的数组覆盖数组

c - 分配字符串时指针存储什么地址?

c++ - 通过引用修改数组后,为什么它保持不变?

c++ - 在 RegExp 中使用星号来提取包含在特定模式中的数据

c++ - 设置条件时 lldb 失败

c# - 如何在 C# 中使用 3 个数组分配变量

arrays - postgresql数组类型是否保留数组的顺序?