在 C++ 中另一个类的方法中使用实例的变量
Using a Variable of an Instance within the Method of another Class in C++
我想知道如何在另一个类的函数中使用一个类的特定实例的变量。
为了提供我正在尝试做的事情的示例,假设我有 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 c
和class b
没有声明为class a
friend
,它们不能直接从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
};
相关文章:
- 返回 C++ 中的指针实例变量
- 返回实例变量的c++方法可以访问变量中的数据,但不能更改它,但在编译时不会生成错误
- C++ 实例变量初始值设定项中的重复类型
- 为什么可以在没有实例变量的情况下访问静态回调方法中的静态成员变量?
- C++ 中实例变量的双冒号
- 我可以在没有任何实例变量的情况下使用 decltype 吗?
- OpenMP 私有类实例变量
- C 取消实例变量指针
- 在C++私有区域中初始化实例变量
- 如何将指针存储在实例变量中,该指针被声明为指向基类的指针
- 如何在Arduino中创建另一个类库的实例变量
- 单元测试呼叫实例变量的函数
- 为构造函数初始化引用实例变量提供默认值
- 如何使编译器在实例变量未初始化时C++生成错误或警告
- 如何超载分配运算符,该操作员总计两个实例变量
- C++:通过引用传递或使用私有实例变量
- 对象作为类内的实例变量
- 在不构造实例变量的情况下C++声明实例变量的好方法是什么?
- 实例变量列表中的对象未被保留?指针问题
- Asio完成处理程序中的实例变量无效