c++ 多态

一、什么是多态

多态(Polymorphism)源自于希腊语,意思是“多种形状”。在C++中,允许通过基类型的指针引用去访问派生对象中的函数,并允许需要执行的函数在运行时进行延迟绑定(Late binding),这称之为多态。多态的前提条件是继承。

另外, 对于重载(overload)的实现也可称之为多态,只不过发生在静态编译阶段,根据函数参数类型的区别就确定了应该调用的函数。

二、原理

基类中含有virtual 修饰的成员函数,编译器将在内存模型中的添加虚函数表的指针(vptr),其占用sizeof(void *)大小(跟平台相关)。该vptr指向存储在别处的虚函数表(vtbl),vtbl中又存放着类中的虚拟成员函数的地址。

三、示例

#include<iostream>
using namespace std;

class Material_thing{
public:
	virtual void hello(){
		cout<<"Material_thing!"<<endl;
	}
};

class Book: public Material_thing{
public:
	void hello(){
		cout<<"Books!"<<endl;
	}
};

int main(){
	Book book;
	Material_thing thing1 = book;
	Material_thing& thing2 = book;
	Material_thing* pThing = &book;
	
	thing1.hello();
	thing2.hello();
	pThing->hello();
	book.hello();

	return 0;
}

hello Material_thing!
hello Books!
hello Books!
hello Books!

posted on 2023-01-14 17:37  七昂的技术之旅  阅读(140)  评论(0)    收藏  举报

导航