面试问题的网站有以下问题:
class Something {
public:
Something() {
topSecretValue = 42;
}
bool somePublicBool;
int somePublicInt;
std::string somePublicString;
private:
int topSecretValue;
};
有必要[在不触及原始类的情况下]获取 的值topSecretValue。这是解决方案:
class SomethingReplica {
public:
int getTopSecretValue() { return topSecretValue; }
bool somePublicBool;
int somePublicInt;
std::string somePublicString;
private:
int topSecretValue;
};
int main(int argc, const char * argv[]) {
Something a;
SomethingReplica* b = reinterpret_cast<SomethingReplica*>(&a);
std::cout << b->getTopSecretValue();
}
我的问题是,这样的解决方案有效吗?我们可以转换为任意类吗?如果没有,这个问题是否有有效的解决方案?