我有以下课程:
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)
我知道这是不好的做法.但出于好奇:这是否有效?它是否定义了行为?
奖金问题:你有没有必要使用这样一个丑陋的黑客?