指针访问类的私有成员

#include <iostream>

using namespace std;

class A
{
private:
	int m_a;
	int m_b;

public:
	A():m_a(0),m_b(0)
	{

	}

	int Get_a()
	{
		return m_a;
	}

	int Get_b()
	{
		return m_b;
	}

	int Set_a(int ate)
	{
		m_a = ate;
		return m_a;
	}
};

typedef int (A::*Fun)(int);

int main()
{
	A test;
	cout<<"test.a = "<<test.Get_a()<<endl;
	cout<<"test.b = "<<test.Get_b()<<endl;
	cout<<"address of &test : "<<&test<<endl;
	cout<<"address of &test+1 : "<<&test+1<<endl;
	cout<<"sizeof(int) : "<<sizeof(int)<<endl;
	cout<<"sizeof(A) : "<<sizeof(A)<<endl;
	int* privateA = reinterpret_cast<int*>(&test);
	int* privateB = reinterpret_cast<int*>(&test) + 1;

	*privateA = 1;
	*privateB = 2;

	cout<<"test.a = "<<test.Get_a()<<endl;
	cout<<"test.b = "<<test.Get_b()<<endl;

	cout<<"-------------------"<<endl;
	Fun pFun = &A::Set_a;
	cout<<"(test.*pFun)() : "<<(test.*pFun)(14)<<endl;
	

	return 0;
}
结果:通过指针和成员函数指针可以访问类的私有成员

你可能感兴趣的:(include,fun)