我将如何从这个抽象类创建一个子类?Vtable 错误

How would I create a sub class from this abstract class ? Vtable Error

本文关键字:一个 子类 错误 Vtable 创建 抽象类      更新时间:2023-10-16

我只是一个试图学习C++的初学者。我正在尝试解决以下问题。我不知道是什么导致了这个问题。

这是我得到的抽象类:

#ifndef __EXPR_H__
#define __EXPR_H__
#include <string>
class Expr {
 public:
  virtual int eval() const = 0;
  virtual std::string prettyPrint() const = 0;
  virtual ~Expr();
};
#endif

我正在尝试创建此类的子类,我的.h文件如下所示

#ifndef __NUM_H__
#define __NUM_H__
#include <iostream>
#include "expr.h"
//class of lone expression
class Num:public Expr
{
private:
    int operand;
public:
    Num(int operand):operand(operand){}
    int eval() const;
    std::string prettyPrint() const;
    ~Num(){}
};
#endif

虽然我对 Num 类的实现看起来像这个"num.cc"

#include "num.h"
#include <sstream>
std::string Num::prettyPrint()
{
    std::stringstream convert;
    convert << operand;
    return convert.str();
}
int Num::eval()
{
    return operand;
}

我不断收到以下错误。我不知道是什么原因造成的。

Undefined symbols for architecture x86_64:
  "vtable for Num", referenced from:
      Num::Num(int) in rpn-dc20fb.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
  "vtable for Expr", referenced from:
      Expr::Expr() in rpn-dc20fb.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

任何帮助将不胜感激。谢谢!

虚拟析构函数需要一个实现

virtual ~Expr() { }

编译器尝试在给定虚拟(纯或非)析构函数的情况下构建虚拟表,并且由于找不到实现而抱怨。

除了由P0W指定之外,函数"eval"和"prettyPrint"还需要在"num.cc"中定义为"const"

std::string Num::prettyPrint() const
{
    std::stringstream convert;
    convert << operand;
    return convert.str();
}
int Num::eval() const
{
    return operand;
}