c++ - 继承实现不起作用

标签 c++ inheritance polymorphism

我有一个名为 Generator 的界面,如下所示:

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;
}

我正在尝试从我的 Note 类(它有一个生成器成员)调用 getSample 方法

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

最佳答案

您似乎从未初始化成员 Note::generator ,所以在其上调用函数是未定义的行为。

尝试,作为测试:

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

如果可行,请返回并检查您的逻辑。使用 std::unique_ptr<Generator>而不是原始指针。为 Node 创建构造函数.在那里初始化指针。

关于c++ - 继承实现不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13198526/

相关文章:

c++ - 从文件到 float 的文本

c++ - 多次从第一行读取文本文件(C++)

c++ - 在 getter 函数中返回 const 引用或拷贝?

c++ - 将二维数组转换为指针到指针

java - 解释一下Java中的多态性?

c++ - 类的前向声明/不完整类型的无效使用

html - 如何在 css 中设置特定段落元素的样式而不影响同一类中的其他段落?

c# - Java 与 C# 方法/函数返回类型重写?

c++ - std::any 是否使用类型删除、子类型化或多态性?

types - Fortran: 'select type'子句中​​的参数化派生类型