简单介绍下c++中成员变量的指针和成员函数的指针

成员变量的指针和成员函数的指针是记录一个变量或函数在类中的偏移量地址,在调用时用一个类的实例加上这个偏移量来调用这些变量或函数。当然c++的private,protected,public对他都是有限制,因为不能直接直接取到非public成员的偏移量。

一段绕人的代码

class foo;
class bar;

class foo
{
public:
	int bar::* m_node;
	void print_bar_i(bar &b)
	{
		std::cout << b.*m_node << std::endl;
	}
};

class bar;
typedef int (bar::*PF)();

class bar
{
public:
	int i;

	int print_i()
	{
		std::cout << i << std::endl;
		return i;
	}

	int j;
private:

	int print_j()
	{
		std::cout << "hello";
		std::cout << j << std::endl;
		return j;
	}
	friend PF bind_print_j(PF pf);
};



PF bind_print_j(PF pf)
{
	pf = &bar::print_j;
	return pf;
}

int main()
{
	// 指向成员变量的指针 case 1 & 2
	{
		//case 1
		std::cout << "case 1:" << std::endl;
		foo f;
		bar b;
		b.i = 10;
		f.m_node = &bar::i;

		f.print_bar_i(b);
	}

	{
		//case 2
		std::cout << "case 2:" << std::endl;
		bar b;
		b.i = 11;
		int bar::*p_bar_int = &bar::i;
		int* p_int = &b.i;

		std::cout << b.*p_bar_int << std::endl;

		std::cout << *p_int << std::endl;
	}

	// 指向成员函数的指针
	{
		//case 3
		std::cout << "case 3:" << std::endl;
		bar b;
		b.i = 12;
		int (bar::*pf_bar_print_i)();

		pf_bar_print_i= &bar::print_i;

		(b.*pf_bar_print_i)();
	}

	{
		//case 4
		std::cout << "case 4:" << std::endl;
		bar b;
		b.j = 13;
	 	int (bar::*pf_bar_print_j)();
		//pf_bar_print_j= &bar::print_j; // 编译错 bar::print_j是私有成员
	 	(b.*bind_print_j(pf_bar_print_j))();
	}
}