为什么编译器认为这个类是抽象的(C++)

Why does the compiler think this class is abstract (C++)?

本文关键字:抽象的 C++ 编译器 为什么      更新时间:2023-10-16

我正在写一些东西来说明命令模式。我已经认识到,对于这个计算器实现,所有的二进制运算(加法、减法等)都只是在前两个堆栈项上"执行"一个运算,所以我试图将该逻辑拉到另一个基类(BinaryCommand)中。

我很困惑为什么会出现错误(如下面主函数的注释所示)。非常感谢您的帮助!

class ExpressionCommand
{
public:
    ExpressionCommand(void);
    ~ExpressionCommand(void);
    virtual bool Execute (Stack<int> & stack) = 0;
};

class BinaryCommand : ExpressionCommand
{
public:
    BinaryCommand(void);
    ~BinaryCommand(void);
    virtual int Evaluate (int n1, int n2) const = 0;
    bool Execute (Stack<int> & stack);
};
bool BinaryCommand::Execute (Stack <int> & s) 
{
    int n1 = s.pop();
    int n2 = s.pop();
    int result = this->Evaluate (n1, n2);
    s.push (result);
    return true;
}
class AdditionCommand : public BinaryCommand
{
public:
    AdditionCommand(void);
    ~AdditionCommand(void);
    int Evaluate (int n1, int n2);
};
int AdditionCommand::Evaluate (int n1, int n2)
{
    return n1 + n2;
}

int main()
{
    AdditionCommand * command = new AdditionCommand(); // 'AdditionCommand' : cannot instantiate abstract class
}

Eek,抱歉,在派生类中添加"const"修复了它。

BinaryCommand是抽象的,因为virtual int Evaluate (int n1, int n2) const = 0;被声明为纯。

AdditionCommand不覆盖virtual int Evaluate (int n1, int n2) const = 0;,因此类缺少纯虚拟成员的定义,因此是抽象的。

int AdditionCommand::Evaluate (int n1, int n2);不会覆盖virtual int Evaluate (int n1, int n2) const = 0;,但会隐藏它。