访问从成员函数返回的私有嵌套类 [英] Access to private nested class returned from member function

查看:88
本文介绍了访问从成员函数返回的私有嵌套类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我理解为什么类成员函数可以返回私有嵌套类对象,以及为什么随后可以在该私有嵌套类上调用成员函数,例如:

Please help me understand why it is possible for a class member function to return a private nested class object, and why it is then possible to call member functions on that private nested class, eg:

class Y
{
    class X
    {
    public:
        void f() { cout << "Hello World" << endl; }
    };

public:
    X g() { return X(); }
};

void h()
{
    Y::X x;     // Error, as expected: class Y::X is private.
    x.f();      // Error.

    Y y;        // OK.
    y.g().f();  // OK. But why???
}

我用GCC和Visual C ++进行了测试,最后一行在这两者上进行了编译。我似乎在C ++标准中找不到任何可以使之有效的东西。知道为什么这样做有效吗?

I tested with GCC and Visual C++, and that last line compile on both. I cannot seem to find anything in the C++ standard that would make this valid. Any ideas why this works?

编辑:

另一种观察结果:

void i()
{
    Y y;

    Y::X x2 = y.g(); // Error: class Y::X is private
    x2.f();          // Error

    auto x3 = y.g(); // OK
    x3.f();          // OK
}


推荐答案

进行嵌套类 private 并不意味着外部作用域永远不能使用该类的实例。访问说明符会影响名称,并且您的 main 函数永远不会尝试输入 name Y :: X 1 唯一命名 Y :: X 的位置是在 Y ,当然可以访问它自己的 private 成员。该函数将 Y :: X 的实例返回到 main 的实例并不特别重要。

Making a nested class private doesn't mean external scopes can never use an instance of that class. Access specifiers affect names, and your main function never attempts to name Y::X.1 The only place where Y::X is named is within Y, which of course has access to its own private members. That the function returns an instance of Y::X to main isn't particularly relevant.


[C ++ 14:11/1]:一个类的成员可以是


  • private ;也就是说,名称只能由声明其的类的成员和朋友使用

  • 受保护的;也就是说,它的名称只能由声明该类的成员和朋友,该类的派生类及其朋友使用(请参见11.4)。

  • public ;也就是说,它的名称可以不受访问限制地在任何地方使用。

  • private; that is, its name can be used only by members and friends of the class in which it is declared.
  • protected; that is, its name can be used only by members and friends of the class in which it is declared, by classes derived from that class, and by their friends (see 11.4).
  • public; that is, its name can be used anywhere without access restriction.

诚然,该标准没有有任何文本可以明确地使您感到困惑,并指出对实体本身的访问不受这些关键字的控制,但这绝对是目的,最终,就法人而言也是如此。

Admittedly, the standard does not have any text to explicitly unconfuse you and point out that access to the entities themselves is not controlled by these keywords, but that is definitely the intent and, ultimately, as far as the legalese goes.

1 它确实命名为 Y :: X :: f ,但名称为公开

1 It does name Y::X::f, but that name is public.

这篇关于访问从成员函数返回的私有嵌套类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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