初始化结构数组时出现问题

时间:2010-06-06 06:01:42

标签: c++ struct

我正在尝试初始化以下结构的以下数组,但我的代码没有编译。有人可以帮帮我吗?

struct / array:

struct DiningCarSeat {
    int status;
    int order;
    int waiterNum;
    Lock customerLock;
    Condition customer;

    DiningCarSeat(int seatNum) {
        char* tempLockName;
        sprintf(tempLockName, "diningCarSeatLock%d", seatNum);
        char* tempConditionName;
        sprintf(tempConditionName, "diningCarSeatCondition%d", seatNum);
        status = 0;
        order = 0;
        waiterNum = -1;
        customerLock = new Lock(tempLockName);
        customer = new Condition(tempConditionName);
    }
} diningCarSeat[DINING_CAR_CAPACITY];

相关错误:

../threads/threadtest.cc: In constructor `DiningCarSeat::DiningCarSeat(int)':
../threads/threadtest.cc:58: error: no matching function for call to `Lock::Lock()'
../threads/synch.h:66: note: candidates are: Lock::Lock(const Lock&)
../threads/synch.h:68: note:                 Lock::Lock(char*)
../threads/threadtest.cc:58: error: no matching function for call to `Condition::Condition()'
../threads/synch.h:119: note: candidates are: Condition::Condition(const Condition&)
../threads/synch.h:121: note:                 Condition::Condition(char*)
../threads/threadtest.cc:63: error: expected primary-expression before '.' token
../threads/threadtest.cc:64: error: expected primary-expression before '.' token
../threads/threadtest.cc: At global scope:
../threads/threadtest.cc:69: error: no matching function for call to `DiningCarSeat::DiningCarSeat()'
../threads/threadtest.cc:51: note: candidates are: DiningCarSeat::DiningCarSeat(const DiningCarSeat&)
../threads/threadtest.cc:58: note:                 DiningCarSeat::DiningCarSeat(int)

提前致谢!

2 个答案:

答案 0 :(得分:1)

ConditionLock没有默认构造函数。您应该使用initialization list来构建它们。

我会更改/添加ConditionLock的构造函数,以便他们可以接受const char*int。然后DiningCarSeat将如下所示:

DiningCarSeat(int seatNum) : 
  status(0), 
  order(0), 
  waiterNum(-1), 
  cutomerLock( "diningCarSeatLock", seatNum), 
  customer("diningCarSeatCondition", seatNum) 
{}

答案 1 :(得分:1)

这里有多个问题:

这些都应该是指针,因为你在构造函数中new

Lock customerLock;
Condition customer;

您没有为seatNum声明类型:

DiningCarSeat(seatNum) {

您不为tempLockNametempConditionName分配内存:

    char* tempLockName;
    sprintf(tempLockName, "diningCarSeatLock%d", seatNum);
    char* tempConditionName;
    sprintf(tempConditionName, "diningCarSeatCondition%d", seatNum);
相关问题