我们都知道为了实现数据封装,添加了private,protected,public三种访问限定符。
在类的外部对应private和protected直接通过对象名和相应类类型的指针是不能访问私有成员的。
但是,我们可以通过特殊方法来读取私有成员。
#include "pch.h"
#include <iostream>
#include<string>
using namespace std;
class student {
public:
student(int a=0,int b=0):
weight(a),age(b){}
void display()const {
cout << weight << endl<< age << endl;
}
private:
int weight;
int age;
};
int main()
{
student g(120, 22);
g.display();
//这里可以通过指针来访问对象私有成员内容哦
int* h = (int*)&g;
cout << *h << endl;
//地址偏移
h = h + 1;
cout << *h << endl;
}
通过改变指向对象指针的类型,我们可以进行读取和修改内容。
并且可以通过一定的地址偏移来读取其他的内容。
程序的执行结果如下: