我有以下的类:
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;
我知道这是不好的实践。但只出于好奇:这个是有保证可以工作吗?它是定义好的行为吗?
额外问题:你曾经必须使用过这样丑陋的hack吗?
BritneySpears::getValue()
和AshtonKutcher::getValue()
简单地返回0,就可以大大优化此代码。 - SyntacticBritneySpears
,我给予赞赏(+1)。请注意,我的翻译尽量保持原意不变,同时使文本更易懂。 - Hugh Brackett