从这个问题的讨论如何在C++中实现私有变量的访问?我提出了一个变体:可以通过强制转换并依赖布局兼容性来调用私有成员函数,而不是访问私有数据成员吗?
一些代码(灵感来自Herb Sutter的列使用和滥用访问权限)
#include <iostream>
class X
{
public:
X() : private_(1) { /*...*/ }
private:
int Value() { return private_; }
int private_;
};
// Nasty attempt to simulate the object layout
// (cross your fingers and toes).
//
class BaitAndSwitch
// hopefully has the same data layout as X
{ // so we can pass him off as one
public:
int Value() { return private_; }
private:
int private_;
};
int f( X& x …Run Code Online (Sandbox Code Playgroud)