看看这个小的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
函数中未正常运行。为什么会这样?