访问私有嵌套类 [英] Accessing private nested class

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

问题描述

我做了一个简单的课程,至今仍在我脑海中玩耍:

I made this simple class, which still is playing with my mind:

class A {
private:
    class B {};

public:
    B getB() {
        return B();
    };
};

从C ++ 03开始,此类可以很好地编译,但是在某种意义上,没有好看的方式getB()的结果分配给左值:

As of C++03, this class compiles fine, but there is just no nice looking way to assign the result of getB() to an lvalue, in the sense that:

A::B b = A().getB();

不编译.

我通过使用中间模板以这种方式得到它:

I got it by using an intermediate template, in this fashion:

template <typename T>
struct HideType {
    typedef T type;
};

HideType<A::B>::type b = A().getB();

但是,对于获得A :: B左值变量的简单任务来说,这看起来很糟糕.

But this looks just terrible, for this simple task of getting an A::B lvalue variable.

从C ++ 11开始,这不再是正确的,或者至少在gcc中不再如此.该代码仍然无效:

This is not true anymore as of C++11, or at least it is not with gcc. This code is still not valid:

A::B b = A().getB();

但这有效:

auto b = A().getB();

标准方面是否存在漏洞?

Is there a loophole in the standard respect to this?

推荐答案

从标准第11条(成员访问控制)开始:

From Standard, Clause 11 (Member access control):

一个班级的成员可以是
- 私人的;也就是说,其名称只能由声明它的类的成员和朋友使用.
-受保护;也就是说,其名称只能由其所在类的成员和朋友使用 由派生自该类的类及其朋友声明(请参见11.4).
- 上市;也就是说,其名称可以在不受访问限制的任何地方使用.

A member of a class can be
— 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.

因此,访问控制将应用于名称.

So access control is applied to names.

auto b = A().getB();

根据标准,您不使用私人名称,因此是合法的

you don't use private names, therefore it's legal, according to Standard

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

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