2009-11-15 60 views
0

我在使用C++創建對象時遇到了一些麻煩。我創建了一個名爲Instruction的類,我試圖創建一個新實例,但是我收到編譯器錯誤。C++新操作符。創建一個新實例

類代碼:

class Instruction{ 

    protected: 
    string name; 
    int value; 

    public: 
    Instruction(string _name, int _value); 
    ~Instruction(); 
    void setName(string _name); 
    void setValue(int _value); 
    string getName(); 
    int getValue(); 
    virtual void execute(); 
}; 



//constructor 
inline Instruction::Instruction(string _name, int _value){ 
    name = _name; 
    value = _value; 
} 
//destructor 
inline Instruction::~Instruction(){ 
    //name = ""; 
    //value = 0; 
} 
inline void Instruction::setName(string _name){ 
    name = _name; 
} 

inline void Instruction::setValue(int _value){ 
    value = _value; 
} 

inline string Instruction::getName(){ 
     return name; 
} 

int Instruction::getValue(){ 
    return value; 
} 
inline void Instruction::execute(){ 
    cout << "still have to implement"; 
} 

這是我嘗試創建一個新的對象:

Instruction* inst; 
inst = new Instruction("instruction33", 33); 

我得到以下編譯器錯誤:

functions.h:70: error: no matching function for call to ‘operator new(unsigned int, std::string&, int&)’ 
/usr/include/c++/4.3/new:95: note: candidates are: void* operator new(size_t) 
/usr/include/c++/4.3/new:99: note:     void* operator new(size_t, const std::nothrow_t&) 
/usr/include/c++/4.3/new:105: note:     void* operator new(size_t, void*) 

你們是正確的。這個錯誤來自這行代碼:

instList.push_back(inst); 

其中instList是這樣創建的:

list <Instruction> instList; //#include <list> is in the file 
+0

它完美地編譯我 – Xinus 2009-11-15 03:51:14

+0

我添加了問題在代碼中的位置。當我嘗試將指令添加到指令列表時發生。 – user69514 2009-11-15 03:53:27

+0

你用'g ++'編譯?我試着用'gcc'編譯這段代碼,並且出現了類似的錯誤。 – hbw 2009-11-15 03:53:58

回答

4

inst是一個指針,指示物和instList是教學對象的列表。所以當你嘗試instList.push_back(inst)它不起作用(它期望一個真正的對象不是它的指針)。你應該改爲instList.push_back(*inst)

0

實際上,它看起來像你的錯誤消息不具有任何與您粘貼代碼在你的OP。我有一個非常好的迴應,準備好不傳遞const char *作爲std :: string &參數,但這看起來不像是你的問題。你發佈的內容不足以查明問題。

0

沒有什麼錯,你粘貼代碼,從消息的錯誤說檢查functions.h上線70

0

相反的:

instList.push_back(inst); 

試試這個:

instList.push_back(*inst); 

你試圖把一個指向指令到指令的列表。

+1

如果您仍然存儲該實例的副本,則動態分配原始文件沒有意義。它只是浪費時間(動態分配並不便宜),你必須記得馬上刪除實例。 – UncleBens 2009-11-15 12:21:08

4

我認爲你會更好的不動態創建指令。

list <Instruction> instList; 

instList.push_back(Instruction("instruction33", 33)); 

注意不需要使用新的。
如果你使用新的,你應該刪除指針。
這增加了您尚未準備好的全部複雜程度。

+0

+1我完全同意。 – 2009-11-15 09:42:41

+0

@Martin:這不也取決於範圍嗎?例如,如果這是在一個函數中完成的,即使instList被傳遞迴主程序,單個指令對象將不再存在,對吧?因爲它超出了函數的範圍。 [email protected]:但是,如果這隻會在聲明範圍內使用,則應該執行上述操作。其他方面使用新的也沒關係。 – Aishwar 2009-11-15 14:53:09

+1

@aip:對不起。標準容器實際上會傳入它們傳入的對象的副本。因此,列表中的對象與列表一樣長。 – 2009-11-15 16:28:30

相關問題