C++ 外部类访问内部类的私有 - 为什么禁止 [英] C++ Outer class access Inner class's private - why forbidden

查看:82
本文介绍了C++ 外部类访问内部类的私有 - 为什么禁止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我想知道为什么C++标准允许我们在嵌套类中访问外部类的私有字段,而禁止从外部类访问内部类的私有字段.我明白,这个例子:

Hello I am wondering why C++ standard allows us in nested classes to access outer class's private fields, while it forbids to access inner class's private fields from the outer class. I understand, that this example:

class OuterClass{
public:
    class InnerClass{
    public:
        void printOuterClass(OuterClass& outer) {cout << outer.m_dataToDisplay;};
    };
private:
    int m_dataToDisplay;
};

很好,因为内部类有时会很复杂.但我认为以下场景也可以:

is fine, because thing, that Inner class sometimes can be complicated. But I think following scenario is also fine:

class Algorithm{
public:
    class AlgorithmResults{
    public:
        void readAlgorithmResult();
    private:
        void writeAlgorithmResult();
    };

    void calculate(AlgorithmResults& results, Arguments...){
       //calculate stuff
       results.writeAlgorithmResult(results);
    }
};

对我来说,这种结构非常合理,尽管在 C++ 中是不允许的.我还注意到,一段时间以来,Java 中都允许使用这两个示例,但现在也禁止使用第二个示例.什么原因,第一个例子被允许而另一个被拒绝?

For me this structure makes perfect sense, although it is not allowed in C++. I also noticed, that for some time both were allowed in Java, but now second example is also forbidden. What is the reason, that first example is allowed and another is denied?

推荐答案

本质上,范围内在该范围内声明的名称是有效的,可以直接使用(除非它们被隐藏).代码范围外不能直接使用范围内声明的名称.例如.花括号块之后的代码不能直接使用在该块内声明的变量(间接使用的一个例子是当外部代码可以访问指向花括号块内的静态变量的指针时).

Essentially, within a scope names declared earlier in that scope are valid and can be used directly (unless they're shadowed). Code outside a scope can't directly use names declared inside the scope. E.g. code after a curly braces block, can't directly use variables declared inside that block (an example of indirect use is when the outside code has access to a pointer to a static variable inside the curly braces block).

对于第二个例子,只需让 Algorithm 成为 AlgorithmResultsfriend:

For the second example, just make Algorithm a friend of AlgorithmResults:

class AlgorithmResults
{
    friend class Algorithm;

这篇关于C++ 外部类访问内部类的私有 - 为什么禁止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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