2013-03-08 87 views
0

我想擁有一個對象隊列並稍後修改它們。由於在隊列中進行修改並刪除它們之後,使隊列生成一個副本,它們就會消失。所以我需要一個指向我的對象的指針隊列來解決這個問題(或者我明白)。指向對象c2228的指針的C++隊列錯誤

我的班級:

class process { 
    int waittime; 
    queue<int> cpuburst, iotime; 
    } 

然後,我創建像這樣我的隊列:

process *P1; 
process *P2; 

P1 = new process(//info to fill my P1 with data); 
P2 = new process(//info to fill my P2 with data); 

queue<process *> readyque; 
queue<process *> onCPU; 

readyque.push(P1); 
readyque.push(P2); 

,編譯罰款,但是當我嘗試做任何事情到隊列與.front()或.push()我得到的錯誤C2228: left of '.cpuburst' must have class/struct/union 和我得到的錯誤IntelliSense: expression must have class type爲「onCPU」

在這條線:

x = onCPU.front().cpuburst.front() + y; 

我只是試圖讓X等於什麼都在隊列中的在我的課,這也是對我的onCPU隊列的頂上

回答

3

由於onCPU包含指向上方,當你做front()時,你會得到一個指針。要通過指針訪問對象的成員,使用->

x = onCPU.front()->cpuburst.front() + y; 

因爲你不確定有指針的queue是否是一個好主意,問自己:應該process對象是的部分queue哪些人擁有他們的唯一所有權?或者queue應該簡單地引用其他地方創建的對象?

如果您可以避免動態分配對象,那永遠是件好事。也許std::queue<std::reference_wrapper<process>>將是有用的。

如果你想保持動態分配它們,考慮一個智能指針(如std::unique_ptrstd::shared_ptr)。

如果你堅持原始指針動態分配的對象,不要忘記delete他們。

+0

謝謝您的快速回復。我不知道我做錯了什麼,因爲我發誓我嘗試了 - >操作符!哈哈哦,謝謝你的幫助 – slowsword 2013-03-08 22:37:41

+0

糾正我,如果我錯了,但刪除它,我只是'刪除P1'? – slowsword 2013-03-08 22:39:53

+0

@slowsword正確。 '刪除P1;刪除P2;' – 2013-03-08 22:40:58