1 通过使用从对象开始处的硬编码/手工编码的偏移量构造指针来访问私有成员数据
class Weak
{
public:
Weak() = default;
~Weak() = default;
// 想想如果去掉该函数,外部想修改类中的私有成员变量 m_name 时该如何操作?
void name(const std::string &name) {
m_name = name;
}
std::string name() const {
return m_name;
}
private:
std::string m_name;
};
struct Hacker
{
std::string name;
};
int main()
{
Weak w;
w.name("zeros");
std::cout << w.name() << std::endl;
// 通过构造一个和类布局一样的结构体,通过指针偏移来修改类中的私有成员函数。
Hacker *hacker = reinterpret_cast<Hacker*>(&w);
hacker->name = "xiaoyu";
std::cout << w.name() << std::endl;
return 0;
}
2 . 使用联合体 union
class Point
{
public:
void print() {
std::cout << x << "x" << y << std::endl;
}
private:
int x, y;
};
class Proxy
{
public:
void print() {
std::cout << x << "x" << y << std::endl;
}
public:
int x,y;
};
int main()
{
union
{
Point a;
Proxy b;
} x;
x.a = Point();
x.b.x = 3;
x.b.y = 5;
x.a.print();
return 0;
}
原文地址:https://www.cnblogs.com/cheungxiongwei/p/12099471.html
时间: 2024-10-08 02:49:54