委托私人部分

fre*_*low 12 c++ pimpl-idiom private delegation operator-overloading

有时,C++的隐私概念让我感到困惑:-)

class Foo
{
    struct Bar;
    Bar* p;

public:

    Bar* operator->() const
    {
        return p;
    }
};

struct Foo::Bar
{
    void baz()
    {
        std::cout << "inside baz\n";
    }
};

int main()
{
    Foo::Bar b;   // error: 'struct Foo::Bar' is private within this context

    Foo f;
    f->baz();     // fine
}
Run Code Online (Sandbox Code Playgroud)

自从Foo::Bar就是private,我不能宣布bmain.然而,我可以从方法中调用方法Foo::Bar.为什么这是允许的?这是意外还是设计?


哦等等,它会变得更好:

Foo f;
auto x = f.operator->();   // :-)
x->baz();
Run Code Online (Sandbox Code Playgroud)

即使我不被允许命名类型Foo::Bar,它也适用于auto......


诺亚写道:

在类定义中定义的类型名称不能在没有限定条件的类之外使用.

只是为了好玩,以下是从外面获取类型的方法:

#include <type_traits>

const Foo some_foo();

typedef typename std::remove_pointer<decltype( some_foo().operator->() )>::type Foo_Bar;
Run Code Online (Sandbox Code Playgroud)

Edw*_*nge 6

试图在标准中找到任何可以详细说明的内容,但我不能.我唯一能找到的是9.9:

类型名称遵循与其他名称完全相同的范围规则.特别是,类定义中定义的类型名称不能在没有限定的情况下在其类之外使用.

从本质上讲,Foo :: Bar 的名称是Foo的私有名称,而不是定义.因此,您可以在Foo之外使用Bars,因为该名称是私有的,所以您无法按类型引用它们.

成员的名称查找规则似乎也会对此产生一些影响.我没有看到任何特别引用"嵌套类"的东西,因此他们不会被允许(如果我实际上没有找到任何东西是因为它不在那里).