相关疑难解决方法(0)

可以通过强制转换为布局兼容类型来访问私有成员吗?

从这个问题的讨论如何在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)

c++ casting access-control private-methods c++11

6
推荐指数
1
解决办法
1622
查看次数

标签 统计

access-control ×1

c++ ×1

c++11 ×1

casting ×1

private-methods ×1