虚拟关键字在此cpp程序中似乎不起作用

时间:2018-10-19 15:33:21

标签: c++ oop polymorphism hierarchy

看看这个小的C++程序:

#include <iostream>

#define debugStream std::cout

struct Id {
    Id() {
        debugStream << this->getClassName() << " created\n";
    }

    virtual ~Id() {
        debugStream << this->getClassName() << " destroyed\n";
    }

    virtual std::string getClassName() {
        return "Id";
    }
};


struct D : public Id {
    std::string getClassName() {
        return "D";
    }
};

int main( int argc, const char *argv[] ) {
    Id* i = new D();
    return 0;
}

我希望该程序能够打印:

D created
D destroyed

但它打印:

Id created
Id destroyed

virtual在析构函数中正常运行,但在getClassName函数中未正常运行。为什么会这样?

0 个答案:

没有答案