如何访问与其他类不同的类中的变量

How to access variables in different class from other class

本文关键字:变量 其他 何访问 访问      更新时间:2023-10-16

x不能是静态的

我想要

class A{
  static std::vector<C> vec_ca;
public:
  int x = 6;
`};
class B{
 std::vector<C> vec_cb;
public:
 int x = 7;
};
class C
{
  void foo(){
  int  k = x;
  }
};

, k将根据它的类而定:如果k in vec_ca k = 6;如果k in vec_cb k = 7。有可能做到吗?

有两种方法。你可以像这样使用getter和setter方法:

class B{
 std::vector<C> vec_cb;
public:
  int get_x(){return x;}
private:
  int x = 7;
};

,从另一个类调用get_x。另一种实现方法是使用好友类。你可以输入:

class B{
 std::vector<C> vec_cb;
 friend class A;
private:
  int x = 7;
};