相关疑难解决方法(0)

私人成员黑客定义的行为?

我有以下课程:

class BritneySpears
{
  public:

    int getValue() { return m_value; };

  private:

    int m_value;
};
Run Code Online (Sandbox Code Playgroud)

哪个是外部库(我无法更改).我显然无法改变它的价值m_value,只能读它.即使是衍生BritneySpears也行不通.

如果我定义以下类,该怎么办:

class AshtonKutcher
{
  public:

    int getValue() { return m_value; };

  public:

    int m_value;
};
Run Code Online (Sandbox Code Playgroud)

然后做:

BritneySpears b;

// Here comes the ugly hack
AshtonKutcher* a = reinterpret_cast<AshtonKutcher*>(&b);
a->m_value = 17;

// Print out the value
std::cout << b.getValue() << std::endl;
Run Code Online (Sandbox Code Playgroud)

我知道这是不好的做法.但出于好奇:这是否有效?它是否定义了行为?

奖金问题:你有没有必要使用这样一个丑陋的黑客?

编辑:只是为了吓唬更少的人:我不打算在实际代码中实际执行此操作.我是在想 ;)

c++ casting private-members

22
推荐指数
2
解决办法
1939
查看次数

标签 统计

c++ ×1

casting ×1

private-members ×1