繁体   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