huihut/interview

“如果想通过基类的指针获得派生类的数据类型,基类必须带有虚函数”的疑问

hbsun2113 opened this issue · 1 comments

请解释一下,没有想明白:如果想通过基类的指针获得派生类的数据类型,基类必须带有虚函数。
谢谢!

因为有虚函数的基类才能拥有动态多态特性,如下面例子:

#include <iostream>
#include <typeinfo>

// 非多态
struct Base1 { void foo() {} };
struct Derived1 : Base1 {};

// 多态
struct Base2 { virtual void foo() {} }; 
struct Derived2 : Base2 {};

int main() 
{
	Derived1 d1;
	Base1& b1 = d1;
	std::cout << "non-polymorphic base typeid: " << typeid(b1).name() << '\n';

	Derived2 d2;
	Base2& b2 = d2;
	std::cout << "polymorphic base typeid: " << typeid(b2).name() << '\n';

	return 0;
}

运行输出:

non-polymorphic base typeid: struct Base1
polymorphic base typeid: struct Derived2