我的朋友制作了这段代码,用于访问类的内存并更改私有变量的值。
#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 ++的未定义行为。但有没有它可以让程序员无法做到这一点?
答案 0 :(得分:0)
可以使用专用的模板类,模板类创建一个私有成员并在隐藏的内存位置静态分配它:
template<typename type>
class true_private
{
public:
~true_private()
{
type local;
get_set(-1, local);
}
true_private(type value)
{
type local = value;
get_set(0, local);
}
void get_set(int op, type& value)
{
static type* var = 0;
if( var == 0)
var = new type();
if( op == 0 ) // set
*var = value;
else if(op == 1) // get
value = *var;
else // delete
delete var;
}
type Get()
{
type local;
get_set(1, local);
return local;
}
void Set(type value)
{
type local = value;
get_set(0, local);
}
};
class has_private_variable
{
private:
true_private<int> member1;
public:
has_private_variable()
:member1(5) //initializer list. In case you haven't seen that before
{
}
int getMember1()
{
return member1.Get();
}
};
这只是一个展示模板类功能的练习:)