简体   繁体   English

在C ++中的另一个类的方法中使用实例的变量

[英]Using a Variable of an Instance within the Method of another Class in C++

I was wondering how I would go about using a variable of a specific instance of a class within a function of another class. 我想知道如何在另一个类的函数中使用一个类的特定实例的变量。

To provide an example of what I'm trying to do, say I've 3 classes a,b and c. 为了提供我要执行的操作的示例,请说我有3个类a,b和c。 Class c inherits from class b, and a single instance of b and c are called within a method in class a and b respectively. 类c继承自类b,并且在类a和b中的方法内分别调用b和c的单个实例。 How would I go about using the variable of int pos (see below) within a specific instance of class a in class c? 我将如何在类c的类a的特定实例中使用int pos变量(请参见下文)?

class a
{
    private:
    void B(); //Calls an instance of class c
    int pos; //Variable that I want to use in c
};

class b : public c
{
    private:
    void C(); //Calls an instance of class b
};

class c
{
    private:
    void calculate(int _pos); //Method which requires the value of pos from class a 
};

Help would be greatly appreciated, thank you! 帮助将不胜感激,谢谢!

Your code sample doesn't make much sense for me, and you aren't really clear what you want to achieve. 您的代码示例对我而言没有多大意义,您也不清楚要实现的目标。

"How would I go about using the variable of int pos (see below) within a specific instance of class a in class c?" “我将如何在类c的类a的特定实例中使用int pos变量(见下文)?”

Fact is you can't access any private class member variables from other classes. 事实是您不能从其他类访问任何private类成员变量。

Since class c and class b aren't declared as friend for class a , these cannot access the pos member from a::pos directly. 由于class cclass b没有被声明为class a friend ,因此它们不能直接从a::pos访问pos成员。 You have to pass them a reference to class a; 您必须将他们传递给a class a;参考class a; at some point, and provide public (read access) to pos with a getter function : 在某个时候,并使用getter函数为pos提供公共(读取访问)权限:

class a {
    int pos; //Variable that I want to use in c
public:
    int getPos() const { return pos; } // <<< let other classes read this 
                                       //     property
};

And use it from an instance of class c() like eg (constructor): 并从class c()的实例中使用它,例如(constructor):

c::c(const a& a_) { // <<< pass a reference to a 
   calculate(a_.getPos());
}

I'm not sure if I understand your problem, but if you want to access a member of a class instance from a non-friend non-base class, that member must be exposed of there must be some function that access it. 我不确定是否理解您的问题,但是如果您想从非友善的非基类访问类实例的成员,则必须暴露该成员,并且必须有某些函数可以访问它。 For example: 例如:

class a
{
public:
  int getPos() const { return pos; }
private:
  void B(); //Calls an instance of class c
  int pos; //Variable that I want to use in c
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM