我有以下课程:
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;
我知道这是不好的做法。但只是出于好奇:这能保证有效吗?它是定义的行为吗?
额外的问题:你曾经使用过这么丑陋的黑客吗?