为什么我的destrucror无法调用虚方法?

时间:2017-04-30 10:41:24

标签: c++

请考虑以下内容(我的编译器是Visual Studio 2015):

class myClassA {
public:
    myClassA()
    {
        printf("Build A\n");
    }
    void parentMethod()
    {
        test();
    }
    virtual ~myClassA()
    {
        printf("Delete A\n");
    }
    virtual void test() = 0;
};

class myClassB : public myClassA {
public:
    myClassB()
    {
        printf("Build B\n");
    }
    virtual ~myClassB()
    {
        printf("Delete B\n");
    }
    void test()
    {
        printf("test\n");
    }
};

int main()
{
    myClassA *b = new myClassB();
    b->parentMethod();
    delete b;
    getchar();
    return 0;
}

如果我这样做,一切都很好:

Build A
Build B
test
Delete B
Delete A

但是如果我想在析构函数中调用test(),它将无法编译!

virtual ~myClassA()
{
    printf("Delete A\n");
    test();
}

链接器抱怨:

Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol "public: virtual void __thiscall myClassA::test(void)" (?test@myClassA@@UAEXXZ) referenced in function "public: virtual __thiscall myClassA::~myClassA(void)" (??1myClassA@@UAE@XZ)  PolymorphismTest    D:\dev\PolymorphismTest\PolymorphismTest\PolymorphismTest.obj   1   

为什么会这样?

似乎析构函数不能调用虚方法,而常规方法可以。

0 个答案:

没有答案