簡體   English   中英

為什么嵌套類時不能從內部 class 訪問外部 class 的私有成員?

[英]Why can't I access private members of the outer class from the inner class when nesting classes?

class X
{
    int Xi;

    class Y
    {
        int Yi;

        void func()
        {
            X x;
            x.Xi = 5;
        }
    };

    void func()
    {
        Y y;
        y.Yi = 5;
    //  ^^^^ 'X::Y::Yi': cannot access private member declared in class 'X::Y'
    }
};

我正在學習 Memento 模式,並且在我閱讀的書中指出,實現該模式的一種方法是在Originator class 中編寫Memento class,這樣只有Originator才能訪問Memento class。 當我嘗試應用此方法時,我收到一條錯誤消息,告訴我私有成員不可訪問。 我知道我可以使用關鍵字friend ,這將使我可以訪問私人成員。 我也知道我可以從內部 class 訪問外部類的私有成員。 但是為什么內部 class 不能訪問內部 class 的私有成員呢?

例如,我可以在 java 中執行此操作:

public class X {

    int Xi;

    public class Y
    {
        private int Yi;

        public void func()
        {
            X x = new X();
            x.Xi = 5;
        }
    }

    public void func()
    {
        Y y = new Y();
        y.Yi = 5;
    }
}

為什么在 C++ 中不可行?

盡管你的問題的標題,你試圖在行y.Yi = 5; 是從外部class 的主體訪問內部class 的私有成員。 你不能這樣做,因為Yi成員是私有的 - 所以它只能從它的 class 內部訪問。

另一方面,行x.Xi = 5; 確實從內部class 訪問外部class 的私有成員; 這個,你可以這樣做,因為你的內部Y class 是外部X class 的一部分。

解決此問題的一種方法是將X::func() function 聲明為class Y朋友 however, you will then need to provide a 'prototype' of that function before you make that declaration, and you would thus need to make the actual definition of the function outside the class body (it must come after the class Y declaration, as it使用該類的 object):

class X {
private: // Even without this line, members are private by default!
    int Xi;
    void func(); // Just a declaration (prototype) - wwwe still need the definition
    class Y {
    private:
        int Yi;
        void func() {
            X x;
            x.Xi = 5;
        }
        friend void X::func();
    };
};

void X::func() { // This is the actual definition of the function.
    Y y;
    y.Yi = 5;
}
#include <iostream>

using namespace std;

class X
{
    public:
    int Xi;

    class Y
    {
        public:
        int Yi;

        void func()
        {
            X x;
            x.Xi = 5;
        }
    };

    void func()
    {
        Y y;
        y.Yi = 5;
    }
};

在這段代碼中,我剛剛公開了 class 成員。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM