超越private

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值