【发布时间】:2011-02-19 12:51:59
【问题描述】:
我有以下课程:
class BritneySpears
{
public:
int getValue() { return m_value; };
private:
int m_value;
};
这是一个外部库(我无法更改)。我显然无法更改m_value 的值,只能读取它。即使从 BritneySpears 派生也行不通。
如果我定义以下类会怎样:
class AshtonKutcher
{
public:
int getValue() { return m_value; };
public:
int m_value;
};
然后做:
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;
我知道这是不好的做法。但只是出于好奇:这能保证有效吗?它是定义的行为吗?
额外问题:你曾经用过这么丑陋的黑客吗?
编辑:只是为了吓唬更少的人:我不打算在真实代码中真正做到这一点。我只是想知道 ;)
【问题讨论】:
-
只要让
BritneySpears::getValue()和AshtonKutcher::getValue()简单地返回0就可以大大优化这段代码。 -
@ereOn:哦,我不够聪明,无法指出 C++ 代码中的错误。我指的是,如果这些类正确地模拟了实际的小甜甜布兰妮和阿什顿库彻,它们的值必须为 0。
-
为什么要访问小甜甜的私处? (对不起。我真的很努力,但我无法抗拒。)
-
+1 用于在具有未定义行为的示例中使用
BritneySpears。 -
+1 用于获取布兰妮的私人信息和“丑陋的黑客”在同一句话中。
标签: c++ casting private-members