为什么我可以在课堂外访问私有结构成员

时间:2019-07-05 02:24:55

标签: c++ class union private-members anonymous-struct

当我访问此私有struct成员时,msvc编译器告诉我无法访问该成员,但是我可以成功运行代码。

但是如果我遗弃了struct成员,则代码将无法运行

#include <iostream>
class A{
    union{
         struct{
            char* c;
         };
    };
};

void fun(A* tmp) {
    //like this,note me can't access,but have no error
    tmp->c = new char('a');
}

int main(void) {

    A t;
    fun(&t);
    std::cout << t.c;
    return 0;
}

//can't run,me can't access and have a "can't access" error
class A{
....
private:
    union{

    };
    struct{
        char* c; 
    };
....
};

txt输出

1>------ Build started: Project: c++11test, Configuration: Debug x64 ----- 
-
1>  main.cpp
1>d:\wirbelwind\documents\visual studio 
2015\projects\json\c++11test\main.cpp(52): warning C4091: 'static ': ignored 
on left of 'a' when no variable is declared
1>  c++11test.vcxproj -> D:\Wirbelwind\Documents\Visual Studio 
2015\Projects\json\x64\Debug\c++11test.exe
1>  c++11test.vcxproj -> D:\Wirbelwind\Documents\Visual Studio 
2015\Projects\json\x64\Debug\c++11test.pdb (Full PDB)
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

我已编辑代码,此代码可以测试。 我使用vs2015(tool v140)

0 个答案:

没有答案