在 C++ 中,使其他 classes 能够访问一个 class 中的成员的最佳方法是什么?

What is the best way to enable other classes to access a member in one class in C++?

我正在尝试将一些 classes 从另一个团队的一大段 C++ 代码移植到我们团队的另一段代码。

原来在旧程序里面,有一个全局变量"rawdata",大家可以使用。但是在移植一些classes的时候,师兄让我把"rawdata"放到majorclass里面,用它的构造函数来初始化"rawdata"。 (我猜他希望全局变量越少越好)

但是,我目前的情况是,我不知道如何让其他 class 不传递对象就可以访问 "rawdata"。例如,

class majorpart() {
   int rawdata;
   majorpart(int input) {rawdata = input;};
}

class otherpart() {
   if(rawdate==0)          // Here we don't want an object of class majorpart
       do something;       // Is it possible for us to directly access rawdata?
}

我是 C++ 的新手。谁能给我一些建议? 谢谢

也许您可以将 rawdata 视为静态成员,这意味着它与 class 的对象无关。

class X { static int n; }; // declaration (uses 'static')
int X::n = 1;              // definition (does not use 'static')

根据您的源代码,一个带有单例的示例-class:

class rawdata {
private:
  static int *_instance;
  rawdata() { }
public:
  static const int *instance() {
    if (_instance) return _instance;
    else return (_instance = new int(10));
  }
};

class majorpart {
  majorpart() { };
};

void doSomething() {

}

class otherpart {
  void someFunction() {
    if (rawdata::instance())          // Here we don't want an object of class majorpart
      doSomething();           // Is it possible for us to directly access rawdata?
  }
};

想法是用 class 包裹 rawdata 字段,以控制它的初始化、访问方式等。

您在对 immiao 的回答的评论中提到,您需要 fiddle 使用宏。无论如何你都需要这样做。它在 majorpart 中作为字段、静态字段或在 rawdata 中作为单例包装器并不重要。