2010-06-06 25 views
0

我想初始化下面的結構的下面的數組,但我的代碼沒有編譯。有人可以幫我嗎?問題初始化一個數組結構

的結構/陣列:

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) 

提前感謝!

+0

你有一本書嗎? – GManNickG 2010-06-06 06:55:58

回答

1

有多種問題在這裏:

這些都應該是指針,因爲你是new荷蘭國際集團他們在你的構造函數:

Lock customerLock; 
Condition customer; 

你不申報類型seatNum

DiningCarSeat(seatNum) { 

你不爲tempLockNametempConditionName分配內存:

char* tempLockName; 
    sprintf(tempLockName, "diningCarSeatLock%d", seatNum); 
    char* tempConditionName; 
    sprintf(tempConditionName, "diningCarSeatCondition%d", seatNum); 
+0

感謝您的快速回答! 雖然我有更多的問題... 我不認爲我需要指針customerLock和客戶...我應該如何初始化它們呢? 啊,我還是不習慣於像分配內存這樣的東西,而且從來沒有發現過我自己的東西。謝謝! – Justin 2010-06-06 06:34:41

1

ConditionLock沒有默認的構造函數。您應該使用initialization list來構建它們。

我會改變/爲ConditionLock添加的構造,使他們能夠接受const char*int。然後DiningCarSeat看起來像:

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

那麼這意味着類是否需要默認的構造函數?我以爲我不需要它們,因爲我沒有使用它們...... 什麼是初始化列表? – Justin 2010-06-06 06:36:27

+0

你可以閱讀[here](http://www.cprogramming.com/tutorial/initialization-lists-c++.html)瞭解初始化列表。 – 2010-06-06 06:39:51