类的私有变量

来源:百度知道 编辑:UC知道 时间:2024/05/31 06:04:49
请"神童"给出在类外改变类内私有变量的方法。给出程序实例。
bc:C++实例

#include<iostream>
using namespace std;

class A
{
private:
int a;
int b;
public:
A()
{
a=10;
b=20;
}
void shuchu()
{
cout<<"a="<<a<<" b="<<b<<endl;
}
};
main()
{
A test;
int *p;
p=(int*)&test; //这里修改的是a的值
cout<<"修改前: ";
test.shuchu();
*p=100;
cout<<"修改后: ";
test.shuchu();
return 0;
}

#include<iostream>
using namespace std;

class A
{
private:
int a;
int b;
public:
A()
{
a=10;
b=20;
}
void shuchu()
{
cout<<"a="<<a<<" b="<<b<<endl;
}
};
main()
{
A test;
int *p;
p=((int*)(&test))+1; //这里修改的是b的值
cout<<&q