由STL的Adapter适配器想到C++多态

这几天疫情在家闲来无聊,翻开许久没看的STL开始复读起来。

mem_fun_ref这个函数印象很深。

属于function adapter。

最常见的用法:

#include <iostream> 
#include <vector>
#include <deque>
#include <iterator>
#include <algorithm>

using namespace std;
class base
{
public:
	virtual void dosomething()
	{

	}
	virtual void donextthing()
	{

	}
};

class Int : public base
{
public:
	Int(int i)
		: mI(i)
	{
		
	}
	virtual void dosomething()
	{
		cout << "i等于" << mI << endl;
	}
	void print() const
	{
		cout << "第" << count++ << "个数是" << mI << endl;
	}
private:
	
	static int count;
	int mI;
};

int Int::count = 0;

void main()
{
		int arr[10] = {0,1,2,3,4,5,6,7,8,9};
	vector<int> vec(arr,arr+10);

	for_each(vec.begin(),vec.end(),mem_fun_ref(&Int::print));
	Int* i = new Int(3);
	Int j(5);

	cout << "j的大小为:"<< sizeof(j) << endl;

	printf("address of base::dosomething %x\n", &base::dosomething);
	printf("address of derived::dosomething %x\n", &Int::dosomething);
	printf("address of derived::donextthing %x\n", &Int::donextthing);
	printf("address of derived::print%x\n", &Int::print);
	void(__thiscall Int::* f)(void) = &base::dosomething;

	(i->*f)();//->*的用法,经由对象指针调用
	(j.*f)(); //.*的用法,经由对象调用

}

依次输出容器内的各个对象。

那这到底是怎么实现的呢?

我们给mem_fun_ref传入了函数的地址,这个是Int,派生类的地址。

妈的语言组织能力太差,直接上图,一切尽在不言中

也就是说父类和子类的虚函数的地址是一样的,一个函数占4个字节的内存,并且虚函数都是连续的地址,这样子类就只需要存一个虚函数表和一个偏移就行了,调用的时候才用__thiscall机制,传入this指针,找到其虚函数表,再调用!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

parkseyoung

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值