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

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

本文关键字:实例 变量 方法 另一个 C++      更新时间:2023-10-16

我想知道如何在另一个类的函数中使用一个类的特定实例的变量。

为了提供我正在尝试做的事情的示例,假设我有 3 个类 a、b 和 c.类 c 继承自类 b,b 和 c 的单个实例分别在类 a 和 b 的方法中调用。我将如何在类 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 
};

帮助将不胜感激,谢谢!

你的代码示例对我来说没有多大意义,而且你也不清楚你想要实现什么。

"我将如何在 C 类中 a 类的特定实例中使用 int pos 变量(见下文)?">

事实上,您不能从其他类访问任何private类成员变量。

由于class cclass b没有声明为class afriend,它们不能直接从a::pos访问pos成员。您必须在某个时候向它们传递对class a;的引用,并使用 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
};

并从class c()实例中使用它,例如(构造函数):

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

我不确定我是否理解您的问题,但是如果您想从非友元非基类访问类实例的成员,则必须公开该成员必须有一些函数可以访问它。例如:

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
};