0
我的朋友创建了这个代码,它将访问类的内存并更改私有变量的值。C++访问内存类并更改私有变量
#include <iostream>
using namespace std;
class has_private_variable
{
private:
const int member1;
public:
has_private_variable()
: member1(5) //initializer list. In case you haven't seen that before
{
}
int getMember1()
{
return member1;
}
};
int main()
{
has_private_variable hpv;
int tmp = hpv.getMember1();
cout << hpv.getMember1() << endl;
char* ptr = (char*)&hpv; //Yeah this will generate all types of warnings hopefully
//find the actual address of the member
while (*(int*)ptr != tmp)
ptr++;
int* ptr_int = (int*)ptr;
*ptr_int = 3;
cout << hpv.getMember1() << endl;
//There's a joke in here about hpv.vaccinate(), but I can't be bothered to find it
return 0;
}
这样做的能力看起来好像破坏了拥有私有变量的整个观点。 有没有一些方法来阻止程序员能够像这样访问私有变量?
编辑:
从我得到,我的朋友被调用的C未定义行为++的意见。但有没有办法让程序员可能无法做到这一点?
引用@Jerry Coffin:“C++试图预防事故,而不是故意颠覆(又名”保护墨菲,而不是马基雅维利“)。” – vsoftco 2014-11-21 18:55:37
或者:C++不会阻止你做任何你想做的事情(必须完成的事情)。它只会警告你,如果它看起来很危险,你没有声称你是对的。 – Deduplicator 2014-11-21 18:59:19
你的朋友已经调用了未定义的行为,它纯粹的机会有访问私有变量的效果。 [阅读关于未定义的行为](http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior)。 – 2014-11-21 19:54:36