委托到私人部分 [英] delegating into private parts

查看:145
本文介绍了委托到私人部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候,C ++的隐私概念只是让我很困惑: - )

  class Foo 
{
struct Bar;
Bar * p;

public:

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

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

int main()
{
Foo :: Bar b; // error:'struct Foo :: Bar'在此上下文中是私有的

Foo f;
f-> baz(); // fine
}

由于 Foo :: Bar private ,我不能在中声明 b $ c>。但是我可以从 Foo :: Bar 调用方法很好。为什么这是允许的?这是意外还是设计?






等待,效果会更好:

  Foo f; 
auto x = f.operator->(); // :-)
x-> baz();即使我不允许命名类型 Foo :: Bar / code>,它适用于 auto ...






Noah写道:


在类定义中定义的类型名称不能在没有限定的类别之外使用。


只是为了好玩,这里是如何从外面得到类型:

  #include< type_traits> 

const Foo some_foo();

typedef typename std :: remove_pointer< decltype(some_foo()。operator->())> :: type Foo_Bar;


解决方案

尝试在标准中找到可拼写的内容详细但我不能。我可以找到的唯一的事情是9.9:



类型名称服从与其他名称完全相同的范围规则。



实质上, 的名称 Foo :: Bar是Foo的私有,不是定义。因此,你可以使用Foo之外的Bars,你只能根据类型引用它们,因为该名称是私有的。



成员的名称查找规则也似乎对此有一定的影响。我没有看到任何具体引用嵌套类,因此他们不会被允许(如果我缺乏找到任何事实,是因为它不在那里)。


Sometimes, C++'s notion of privacy just baffles me :-)

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
}

Since Foo::Bar is private, I cannot declare b in main. Yet I can call methods from Foo::Bar just fine. Why the hell is this allowed? Was that an accident or by design?


Oh wait, it gets better:

Foo f;
auto x = f.operator->();   // :-)
x->baz();

Even though I am not allowed to name the type Foo::Bar, it works just fine with auto...


Noah wrote:

type names defined within a class definition cannot be used outside their class without qualification.

Just for fun, here is how you can get at the type from outside:

#include <type_traits>

const Foo some_foo();

typedef typename std::remove_pointer<decltype( some_foo().operator->() )>::type Foo_Bar;

解决方案

Trying to find anything in the standard that would spell it out in detail but I can't. The only thing I can find is 9.9:

Type names obey exactly the same scope rules as other names. In particular, type names defined within a class definition cannot be used outside their class without qualification.

Essentially, the name of Foo::Bar is private to Foo, not the definition. Thus you can use Bars outside of Foo, you just can't refer to them by type since that name is private.

The name lookup rules for members would also seem to have some effect on this. I don't see anything that specifically references "nested class" and thus they wouldn't be allowed to (if my lack of finding anything in fact is because it's not there).

这篇关于委托到私人部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆