2012-11-02 211 views
1

我有一個接口稱爲發電機,看起來像這樣:繼承執行不工作

class Generator{ 
public: 
    virtual float getSample(Note &note)=0; 
}; 

而且我Synth類實現它,像這樣:

class Synth : public Generator{ 
public: 
    virtual float getSample(Note &note); 
}; 

float Synth::getSample(Note &note){ 
    return 0.5; 
} 

我想打電話給getSample方法從我的Note類(它有一個生成器成員)

class Note : public Playable{ 
public: 
    Generator *generator; 
    virtual float getValue(); 
}; 

float Note::getValue(){ 
    float sample = generator->getSample(*this); // gets stuck here 
    return sample; 
} 

當我嘗試運行時,它會卡在上面代碼的標記行中。問題是我沒有得到一個非常明確的錯誤信息。這是我可以看到,一旦它停止:

enter image description here enter image description here

+0

您確定生成器成員已初始化('EXC_DAB_ACCES'似乎表明不然)?你也應該使用智能指針而不是原始指針。 – stijn

回答

4

好像你從來沒有初始化的成員Note::generator,所以調用一個函數它是不確定的行爲。

嘗試,作爲一個測試:

float Note::getValue(){ 
    generator = new Synth; 
    float sample = generator->getSample(*this); // gets stuck here 
    return sample; 
} 

如果一切正常,回去檢查你的邏輯。使用std::unique_ptr<Generator>而不是原始指針。創建一個構造函數Node。在那裏初始化指針。

+0

它使用'generator = new Synth;',我沒有正確初始化'generator',就像你說的那樣。它實際上指向另一個空指針。感謝您的幫助 – networkprofile

+0

@Sled沒關係,那麼你知道你必須做什麼:) –

+0

是的,我會看看unique_ptr了,不知道這一點。 – networkprofile