簡體   English   中英

通過類級別訪問私有變量。

[英]Accessing private variables through levels of classes.

因此,以我目前對如何正確使用封裝的理解,將變量設為私有並通過此類的成員函數訪問變量是一個很好的經驗法則:

class Aclass{
private:
    int avar;
public:
    void ch_avar(int val){avar = val};
    int get_avar() {return avar;}
};

我的問題是我將如何訪問一個類實例的私有成員,而該實例本身就是另一個類的私有成員。 這是我嘗試執行此操作的示例(為簡潔起見,不重新鍵入上面的示例)

class LargerClass{
private:
    int other_var;
    Aclass A; //has two instances of class "Aclass" 
    Aclass B; 
public: 
    void ch_other_var(int val){other_var = val;}
    int get_other_var() {return other_var;}

     // this is the important line for the question
    int get_avar(Aclass X){return X.get_avar();} 
}; 

現在,在我的真實程序中,還有更多級別,並且不斷收到“ Aclass”是未知類型的編譯錯誤。 即使我在Larger類中包含了Aclass的頭文件。 因為我被困住了,所以我認為最好找出這是否是做我想要的正確(或可接受的方式)。 我是OOP的新手,對我來說這很草率。

要訪問作為其自身的類實例的私有成員,可以訪問另一實例的私有成員。 您不需要通過AclassX。這是不必要的。 您可以通過給定的實例名稱來調用它。

class LargerClass{
private:
    int other_var;
    Aclass A; //has two instances of class "Aclass" 
    Aclass B; 
public: 
    void ch_other_var(int val){other_var = val;}
    int get_other_var() {return other_var;}

     // this is the important line for the question
    int get_avar_A(){return A.get_avar();} 
}; 

如果您有20個Aclass實例,則可以創建一個Aclass實例向量。

class LargerClass{
private:
    int other_var;
    Aclass A[20]; 
public: 
    void ch_other_var(int val){other_var = val;}
    int get_other_var() {return other_var;}

     // this is the important line for the question
    int[] get_avar_A()
   {
     int other_var[20];
     for(int i= 0; i<20; i++)
     {
       other_var[i] = A[i].get_avar();
     }
     return other_var;
    } 
}; 

暫無
暫無

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

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