虚函数机制

虚函数机制是为了实现动多态,运行时虚表加载到内存中,再从虚表中拿出函数的入口地址 

#include<iostream>
using namespace std;
//基类的指针或者引用可以指向或者引用派生类对象,
//但是派生类的指针或者引用不允许指向或者引用基类对象
class Base
{
public:
	Base(int a) :ma(a)
	{
		//this->show();//静多态
		//cout << "Base::Base()" << endl;
	}
	~Base()
	{
		//this->show();//静多态,一进入析构,对象已经不完整了
		//cout << "Base::~Base()" << endl;
	}
	virtual void show()
	{
		cout << "Base::show()" << endl;
		//cout << ma << endl;
	}
protected:
	int ma;
};
class Derive:public Base
{
public:
	Derive(int b) :mb(b), Base(b)
		//因为基类中没有默认构造函数,所以在此参数列表中要加Base(b)来指明基类的构造方式
	{
		//cout << "Derive::Derive()" << endl;
	}
	~Derive()
	{
		//this->show();
		//cout << "Derive::~Derive()" << endl;
	}
	void show()
	{
		cout << "Derive::show()" << endl;
		//cout << ma << endl;
		//cout << mb << endl;
	}
private:
	int mb;
};


int main()
{
	Base base(10);
	Derive derive(20);
	cout << sizeof(base) << endl;
	cout << sizeof(derive) << endl;
	
	Base* pb = new Derive(10);
	cout << typeid(pb).name() << endl;
	cout << typeid(*pb).name() << endl;

	pb->show();
	
}

基类中show()方法不加virtual关键字的运行结果:

基类中show()方法加virtual关键字的运行结果:

虚函数指针vfptr(优先级最高)并不是直接指向虚函数,而是间接指向虚函数表vftable(虚函数的集合)

基类中是虚函数,派生类中同名且形参类型相同的函数也是虚函数

虚函数表(一个虚表对应一个类,即一个类一个虚表)

猜你喜欢

转载自blog.csdn.net/Aspiration_1314/article/details/86544042
今日推荐