#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
, 但是为什么我能够在外界直接获取结构体内的属性呢? 该结构体对于外界而言不是不可见的吗?
PHP中文网2017-04-17 14:31:50
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;
}
天蓬老师2017-04-17 14:31:50
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