Почему я могу получить доступ к закрытому члену структуры вне класса - PullRequest
2 голосов
/ 05 июля 2019

Когда я получаю доступ к этому приватному члену структуры, компилятор msvc сказал мне, что я не могу получить доступ к члену, но могу успешно выполнить код.

но если я пропустил член структуры, код не может работать

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

текстовый вывод

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 (инструмент v140)

...