2012-11-02 214 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