c++ 类内私有的结构体对于外界而言是公开的?
天蓬老师
天蓬老师 2017-04-17 14:29:50
0
2
575
#include <iostream>
class test{
    private:
        struct tes{
            int te;
        };

        tes t;
    public:
        test(){
            t.te = 5;
        }
        tes* xixi(){
            return &t;
        }
};

int main(void){
    test test1;
    std::cout << test1.xixi()->te;
    return 0;
}

代码如上, 类test中有一个私有的结构体tes, 但是为什么我能够在外界直接获取结构体内的属性呢? 该结构体对于外界而言不是不可见的吗?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
Ty80

Because you made the structure public through xixi(), you directly get the address of the structure object, and you can get the properties of the structure, but you cannot directly access the structure.
Add an example. . . . This example is used to express my thoughts. Local static variables can be modified outside.

#include <iostream>

using namespace std;

int* func()
{
    static int a = 2;
    cout << a << endl;
    return &a;
}

int main()
{
    int* ptr = func();
    *ptr = 3;
    func();
    return 0;
}
Peter_Zhu

Because your xixi() belongs to public, and its return value is of type tes*, which is when the tes type is exposed to the outside world

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template