huihut / interview

📚 C/C++ 技术面试基础知识总结,包括语言、程序库、数据结构、算法、系统、网络、链接装载库等知识及面试经验、招聘、内推等信息。This repository is a summary of the basic knowledge of recruiting job seekers and beginners in the direction of C/C++ technology, including language, program library, data structure, algorithm, system, network, link loading library, interview experience, recruitment, recommendation, etc.

Home Page:https://interview.huihut.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

hbsun2113 opened this issue · 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