C++指向成员的指针-成员指针

指针是指向一些内存地址的变量,既可以是数据的地址,也可以是函数的地址。

C++的成员指针包括数据成员指针和成员函数指针。C++的成员指针不是指向

确切的地址,而是指向类成员在类中的偏移。只有把这个偏移和具体对象的开

始地址结合,才能得到实际的地址。

#include <iostream>
#include <stdlib.h>

using namespace std;

class simple {
public:
	int a;
	int b;

	int f(int f) {
		b += f;
	}
};

int main() {
	//数据成员指针
	int simple::*pa = &simple::a;
	cout << "offset of a = " << pa <<endl;//这里输出为1,想知道为何请看《深度探索C++对象模型》,下同
	
	simple so;
	so.*pa = 4;		//给a赋值
	simple *sp = (simple *)malloc(sizeof(simple));
	sp->a = 2;
	sp->b = 10;
	
	pa = &simple::b;
	
	cout << "so.a = " << so.a <<endl;
	cout << "sp->b = " << sp->*pa <<endl;
	
	//成员函数指针
	int (simple::*f)(int f);
	f = &simple::f;
	
	cout << "offset of f = " << f <<endl;
	(sp->*f)(10);	//调用成员函数
	cout << "sp->b = " << sp->*pa <<endl;
	
	return 0;
}

下面程序主要说明了如何使用成员函数指针:

#include <iostream>
using namespace std;

class widget {
private:
	void f(int) const { cout << "widget::f()" <<endl; }
	void g(int) const { cout << "widget::g()" <<endl; }
	void h(int) const { cout << "widget::h()" <<endl; }
	void i(int) const { cout << "widget::i()" <<endl; }
	
	enum { count = 4 };
	void (widget::*fptr[count])(int) const;
	
public:
	widget() {
		fptr[0] = &widget::f;
		fptr[1] = &widget::g;
		fptr[2] = &widget::h;
		fptr[3] = &widget::i;
	}
	
	void select(int I, int J) {
		if(I < 0 || I >= count)
			return;
		
		(this->*fptr[I])(J);
	}
	
	int Count() { return count; }
};

int main() {
	widget w;
	for(int i = 0; i < w.Count(); i++)
		w.select(i, 47);
	
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值