子类的vptr指针

时间:2022-08-10 21:55:29
#include <iostream>
#include<stdio.h>
using namespace std;

class Parent
{
public:
	Parent(int a = 0)
	{
		this->a = a;
		print();
	}
	virtual void print()
	{
		cout << "我是爹!" << endl;
	}
private:
	int a;
};

class Child :public Parent
{
public:
	Child(int a = 0, int b = 0) :Parent(b)
	{
		this->a = a;
	}
	 void print()
	{
		cout << "我是儿子!" << endl;
	}
private:
	int a;
};

void HoToPlay(Parent *base)
{
	base->print();
}
void main()
{
	Child c1;
	c1.print();
	system("pause");
	return;
}

执行结果:

子类的vptr指针



子类的vptr指针是分步执行的:

子类的vptr指针


如何证明vptr指针的存在?

#include <iostream>
using namespace std;


class Parent1
{
public:
	Parent1(int a = 0)
	{
		this->a = a;
	}

	void print()
	{
		cout << "我是爹" << endl;
	}
private:
	int a;
};

class Parent2
{
public:
	Parent2(int a = 0)
	{
		this->a = a;
	}

	virtual void print()
	{
		cout << "我是爹" << endl;
	}
private:
	int a;
};

void main()
{
	printf("sizeof(Parent):%d \nsizeof(Parent2):%d \n", sizeof(Parent1), sizeof(Parent2));
	cout << "hello..." << endl;
	system("pause");
	return;
}

子类的vptr指针

结论:有虚函数的类,含有一个4bit的指针