链接器抱怨基本抽象类的纯虚析构函数缺乏实现

时间:2018-02-09 18:52:05

标签: c++11 linker abstract-class pure-virtual virtual-destructor

我从this问题中学到的东西,但我认为我会给出一个更详细,更易于搜索的答案,那就是如果你有一个基本的抽象类意味着要继承这样的话,你通过添加" = 0"使你的析构函数变得虚拟纯净。到最后:

class Base {
public:
    virtual ~Base() = 0;
};

并尝试使用它来派生一个类,如下所示:

class Derived : public Base {
public:
    ~Derived();
};

Derived::~Derived() {
    // nothing, this is an example
}

你会得到链接器错误,抱怨基础解析器缺乏实现,尽管它是纯虚方法(在MSVC上你可能会得到LNK2019和LNK 2001错误)。那你怎么解决这个问题呢?

1 个答案:

答案 0 :(得分:0)

答案是你需要提供基础析构函数的实现,尽管它是纯虚函数。推理可以在the question I linked above中找到。

知道这一点,我们可以对基类进行更改,这样就可以了!

class Base {
public:
    virtual ~Base() = 0;
};

// This was added to get rid of the error
Base::~Base() {
    // nothing, although you can add your own code if necessary
}

class Derived : public Base {
public:
    ~Derived();
};

Derived::~Derived() {
    // nothing, this is an example
}