C++ 在基类中声明虚拟析构函数会更改指针指向的类型?

C++ 在基类中声明虚拟析构函数会更改指针指向的类型?,c++,C++,我在编写一个简单的程序来学习虚拟析构函数时遇到了以下行为。我想做的是打印每个类的名称,然后与指针指向的类型进行比较。我将print语句放在每个析构函数中,这样就可以看到基类中在虚拟和非虚拟之间切换时的行为 代码: 但是,当我将TimeKeeper基类析构函数更改为虚拟时,输出如下: TimeKeeper Name: 10TimeKeeper AtomicClock Name: 11AtomicClock ptk is of type: 11AtomicClock I am in the Deri

我在编写一个简单的程序来学习虚拟析构函数时遇到了以下行为。我想做的是打印每个类的名称,然后与指针指向的类型进行比较。我将print语句放在每个析构函数中,这样就可以看到基类中在虚拟和非虚拟之间切换时的行为

代码:

但是,当我将TimeKeeper基类析构函数更改为虚拟时,输出如下:

TimeKeeper Name: 10TimeKeeper
AtomicClock Name: 11AtomicClock
ptk is of type: 11AtomicClock
I am in the Derived Class Destructor
I am in the Base Class Destructor
我理解为什么调用dervied类析构函数,但是我不理解为什么ptk类型发生了变化


我的问题是:当我切换到TimeKeeper类中的虚拟析构函数时,为什么ptk指向的类型会发生变化?还是我不明白typeid是如何工作的/如何使用它?

这与调用虚拟函数和非虚拟函数的区别是一样的。可以使用表达式的类型,也可以使用对象的类型。就

TimeKeeper *ptk = new AtomicClock(rand());
std::cout << "ptk is of type: " << typeid(*ptk).name() << std::endl;
TimeKeeper*ptk=新原子钟(rand());

std::cout没有虚拟析构函数(或基类中的任何虚拟函数)
AtomicClock
不是a,因此
typeid
将使用
*ptk
的静态类型,即
计时器。见2.b)。
TimeKeeper Name: 10TimeKeeper
AtomicClock Name: 11AtomicClock
ptk is of type: 11AtomicClock
I am in the Derived Class Destructor
I am in the Base Class Destructor
TimeKeeper *ptk = new AtomicClock(rand());
std::cout << "ptk is of type: " << typeid(*ptk).name() << std::endl;