A member of a class can be
— private; that is, its name can be used only by members and friends of the class in which it is
declared.
— protected; that is, its name can be used only by members and friends of the class in which it is
declared, and by members and friends of classes derived from this class .
— private; that is, its name can be used only by members and friends of the class in which it is
declared.
— protected; that is, its name can be used only by members and friends of the class in which it is
declared, and by members and friends of classes derived from this class .
— public; that is, its name can be used anywhere without access restriction.
如上所述,如果类内的一个成员变量为私有类型,那么该成员变量只可以被该类的成员函数、或友元函数访问,在类外无法像共有成员变量一样,直接通过类的对象直接访问,但是我们可以通过void指针和该私有变量的偏移来实现对其的访问,实例代码如下所示:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class People{
private:
string name;
string address;
int age;
public:
People(string Name,string Address,int Age)
{
name=Name;
address=Address;
age=Age;
}
void display()
{
cout<<"Name="<<name<<" Address="<<address<<" Age="<<age<<endl;
}
};
int main()
{
People pp("chaochao","NJUST",25);
pp.display();
//cout<<pp.age<<endl; 无法直接访问
void *p = (void *)&pp;
int offset = sizeof(string)+sizeof(string);
char *pAge = (char *)p + offset;
cout<<(int)(*pAge)<<endl;
return 0;
}
运行后,可得运行结果如下:
可见,通过void指针的强制转换和成员的偏移量,我们成功访问了类内的私有成员变量。