#define private public
class Test
{
public:
Test(int i, double d, char c)
{
Init(i, d, c);
}
void Init(int i, double d, char c)
{
_i = i;
_d = d;
_c = c;
}
private:
int _i;
double _d;
char _c;
};
int main()
{
Test test(1, 2.2, 'c');
//访问私有变量方法一
cout << "通过宏访问私有变量" << endl;
cout << "test的私有变量i==========" << test._i << endl;
cout << "test的私有变量d==========" << test._d << endl;//p1是void*不能直接运算
cout << "test的私有变量c==========" << test._c << endl;
cout << endl;
//访问私有变量方法二
cout << "通过指针访问私有变量" << endl;
void* p1 = &test;
cout << "test的私有变量i==========" << *((int*)p1) << endl;
cout << "test的私有变量d==========" << *((double*)(((int*)p1)+2)) << endl;//p1是void*不能直接运算,要转换成特定类型才可以运算
cout << "test的私有变量c==========" << *((char*)(((int*)p1)+4)) << endl;//(4*sizeof(int))Bytes
cout << "test的私有变量c==========" << *((char*)(((double*)p1)+2)) << endl;//(2*sizeof(double))Bytes
cout << endl;
cout << "各种类型变量所占空间大小(字节)" << endl;
cout << "int size===========" << sizeof(int) << endl;//4Bytes
cout << "double size========" << sizeof(double) << endl;//8Bytes
cout << "char size==========" << sizeof(char) << endl;//1Byte
cout << "Test size==========" << sizeof(Test) << endl;//24Bytes,涉及内存对齐,默认是8Bytes对齐
return 0;
}