为什么编译器认为这个类是抽象的(C++)
Why does the compiler think this class is abstract (C++)?
我正在写一些东西来说明命令模式。我已经认识到,对于这个计算器实现,所有的二进制运算(加法、减法等)都只是在前两个堆栈项上"执行"一个运算,所以我试图将该逻辑拉到另一个基类(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;
,但会隐藏它。
相关文章:
- 抽象类错误,请参阅声明" "是抽象的
- C++抽象的字节序是中立的吗?
- 观察者模式:为什么主题应该是抽象的?
- 派生类仍然是抽象的
- 确保课程不是抽象的
- 为什么我的课被认为是抽象的
- 基类为抽象的 ADT 数组
- 继承抽象的基础接口及其实现给出了C2259
- Qt5 有没有办法让QLocalServer监听抽象的Unix套接字
- 在OCAML中,抽象的价格有多大(即多态性功能)
- 这个派生类是如何抽象的
- 为什么 C++11 允许抽象的最终类
- 不能分配抽象类型的对象 - 但类不是抽象的!(C++)
- 有没有办法将抽象的对象投入给孩子
- 如何在编译时间检查课程,是否是抽象的
- 抽象基类具有抽象的嵌套类
- 在C++解释编译器如何能够识别一个类是抽象的还是不抽象的
- 将派生对象添加到(抽象的)基指针数组中
- 函数在C++中永远不能是抽象的吗
- 检测(可能是抽象的)基类的受保护构造函数