[英]Accessing private variables through levels of classes.
So in my current understanding of how to use encapsulation correctly it is a good rule of thumb to make variables private and access them through member functions of the class like this: 因此,以我目前对如何正确使用封装的理解,将变量设为私有并通过此类的成员函数访问变量是一个很好的经验法则:
class Aclass{
private:
int avar;
public:
void ch_avar(int val){avar = val};
int get_avar() {return avar;}
};
My question is how would I access a private member of a class instance which is its self a private member of another class. 我的问题是我将如何访问一个类实例的私有成员,而该实例本身就是另一个类的私有成员。 Here is an example of the way I have been trying to do it (not retyping the example above for brevity)
这是我尝试执行此操作的示例(为简洁起见,不重新键入上面的示例)
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();}
};
Now In my real program there are a few more levels of this and I keep getting the compilation error that "Aclass" is an unknown type. 现在,在我的真实程序中,还有更多级别,并且不断收到“ Aclass”是未知类型的编译错误。 Even though I have included the header file for Aclass in the Larger class.
即使我在Larger类中包含了Aclass的头文件。 Since I am stuck I thought It would be good to find out if this is even the correct (or an acceptable way) of doing what I want.
因为我被困住了,所以我认为最好找出这是否是做我想要的正确(或可接受的方式)。 I am new to OOP and this feels sloppy to me.
我是OOP的新手,对我来说这很草率。
To access the private member of a class instance which is its self a private member of another class, can be done this way. 要访问作为其自身的类实例的私有成员,可以访问另一实例的私有成员。 You don't need to pass a Aclass X. It is unneccessary.
您不需要通过AclassX。这是不必要的。 You can call it by the instance name you have given..
您可以通过给定的实例名称来调用它。
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();}
};
If you have 20 instances of Aclass, rather you create a vector of Aclass instances. 如果您有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.