In the case where only the header files to get, how to modify the value of private members of the class?

1 to access the private members of the hard-coded data from the beginning of the object / hand-coded by using a pointer offset configuration

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. Use of the Commonwealth 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;
}

Guess you like

Origin www.cnblogs.com/cheungxiongwei/p/12099471.html