偷出类里面proteced的虚函数

class empty_class{
private:
	int i;
protected:
	void virtual do_something(){
		cout<<"do somtthing"<<endl;
	}
	void virtual do_another(){
		cout<<"do another"<<endl;
	}
};

int main(int argv, char*args[])
{
	typedef void (*func)();
	empty_class *p_ec = new empty_class();
	int *p = (int *)(p_ec); // *p 是虚函数表的地址 
	int *q = (int *)(*p); // *q 是第一个函数的地址
	func f = (func)(*q);
	f();
	func g = (func)(*q - 4);
	g();
	system("pause");
	return 0;
}

上面的例子偷出了类里面protected修饰的函数;

这个例子对理解对象内存结构有很大帮助。

类里面如果什么都没有,sizeof的结果是1,测试过里面放的是0;

类里面如果仅仅有一个虚函数,那么对象内存里面存的就是虚函数表的指针

将对象指针解引用就是虚函数表的指针,再解引用就是虚函数表的首函数地址。

需要注意虚函数是倒着存的,要得到第二个就要地址减4;

上述代码运行后能执行类里面的那两个虚函数。

原文地址:https://www.cnblogs.com/lovelyxia/p/1912723.html