C++ private modifier ignored on nested anonymous struct

孤人 提交于 2019-12-05 14:17:42

问题


The following sample code compiles just fine in Visual C++:

class Test {
private:
    struct {
        struct {
            int privateData;
        };
    };
};

int main(int, char **)
{
    Test test;
    test.privateData = 0;
    return 0;
}

But why? I'd expect a compiler error because the privateData member should be inaccessible to the function main, since it's supposed to be private like its container's container. I know that nameless structs are not part of official C++, but this design is asinine.

By the way I've also tried to change private into protected and struct into union: it looks like the compiler refuses to honor access modifiers on anonymous structs and unions that are nested inside another anonymous struct or union.

Can someone explain this feature?


回答1:


Yes, it is a bug. Microsoft acknowledged it is, the feedback report is here.

Right now the bug is in "will not fix" status and it is unclear when (if ever) it will be addressed. There is a somewhat odd workaround for it, the IntelliSense parser built into Visual Studio, written by the Edison Design Group, does complain about it. You get the red squiggles and the message:

Error: member "Test.privateData" (declared at line 10) is inaccessible



来源:https://stackoverflow.com/questions/14187647/c-private-modifier-ignored-on-nested-anonymous-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!