C++-- 如何在类外访问一个类中私有的成员变量?

如何在类外访问一个类中私有的成员变量?
我在网上搜答案的时候看到大部分回答都是在类内部创建一个接口,所以此方法我就不再多做赘述,今天我说的方法是利用指针的方法。

话不多说,上代码:

class Test
{
private:
    int a = 10;
    int b = 100;
};

int main()
{
    Test s;
    cout << sizeof(s) << endl;//s为8个字节
    Test* ps = &s;

    int * ps1 = ((int *)ps + 1);
    void* ps2 = (ps + 1);

    system("pause");
    return 0;
}

打开调试中的监视窗口,我们可以看到:
这里写图片描述
s的内容为{a = 10, b = 100},s的地址为0x004ffc20 ;
ps里面存储的内容为0x004ffc20 ,ps的地址为0x004ffc14;
ps1里面存储的内容为0x004ffc24,ps1的地址为0x004ffc08;
ps2里面存储的内容为0x004ffc28,ps2的地址为0x004ffbfc;

通过代码我们推断:
ps代表的是s的首地址,也就是a的位置,因为ps是Test*类型的,而Test的大小为8个字节,所以ps2就代表将ps向后移动了8个字节的位置,而ps1因为强转为int *类型,所以ps1就代表将ps向后移动了4个字节的位置,如此ps1此时指向的就是b的位置

为了验证我的言论,打开调试的内存窗口,输入&s:
这里写图片描述
这与我们的推断一致,了解了这些,我们就可以通过ps1来改变私有成员b的数值了。

class Test
{
public:
    void SetA(int _a)//接口(可以从类外设置a的值)
    {
        a = _a;
    }
    void Print()
    {
        cout << a << endl;
        cout << b << endl;
        cout << endl;
    }
private:
    int a = 10;
    int b = 100;
};

int main()
{
    Test s;
    s.Print();

    s.SetA(0);//通过接口把a设置为0;
    s.Print();

    Test* ps = &s;
    int * ps1 = ((int *)ps + 1);
    *ps1 = 0;//通过指针把b设置为0;
    s.Print();

    system("pause");
    return 0;
}

结果:
这里写图片描述

访问限定符只在编译时有用,当数据映射到内存后,没有任何访问限定符上的区别

猜你喜欢

转载自blog.csdn.net/it_is_me_a/article/details/82014577