我再次在这里寻求支持。
例如,我有一个名为 fp 的 fopen 东西
FILE * fp;
fp=fopen("Entity.dat","wb");
而且我有 x 个函数,并且需要在所有函数中使用这个东西,所以问题是我怎样才能使它成为公共/全局范围。
理想情况下,您应该简单地将它作为参数传递给需要使用它的任何函数:
void func( FILE *f, ... )
{
  // do something with f
}
int main( void )
{
  FILE *fp = fopen( "Entity.dat", "wb" );
  ...
  func( fp, ... );
  ...
}
你应该使用extern:
the_file.h
#ifndef FILE_H
#define FILE_H
...
extern FILE *file;
#endif
the_file.cpp
#include "file.h"
FILE *file;
然后打开文件并将句柄存储在file. 接下来,您可以file在需要的地方使用。
如果你有选择,请把它作为参数传递,如果你真的没有选择,那么你可以考虑单例。
c++11
template<typename T>
class meyersSingleton
{
public:
  static T& instance()
  {
    static T theSingleton;
    return theSingleton;
  }
  meyersSingleton() = delete;
  ~meyersSingleton() = delete;
  meyersSingleton(meyersSingleton const&) = delete;
  meyersSingleton& operator=(meyersSingleton const&) = delete;
};
C++98
template<typename T>
class meyersSingleton
{
public:
  static T& instance()
  {
    static T theSingleton;
    return theSingleton;
  }
private :
  meyersSingleton();
  ~meyersSingleton();
  meyersSingleton(meyersSingleton const&);
  meyersSingleton& operator=(meyersSingleton const&);
};
你可以这样使用它
#include <cstdio>
template<typename T>
class meyersSingleton
{
public:
  static T& instance()
  {
    static T theSingleton;
    return theSingleton;
  }
  meyersSingleton() = delete;
  ~meyersSingleton() = delete;
  meyersSingleton(meyersSingleton const&) = delete;
  meyersSingleton& operator=(meyersSingleton const&) = delete;
};
void read_file()
{
    char buffer [100];
    fgets (buffer , 100 , meyersSingleton<FILE*>::instance());
    printf("%s", buffer);    
}
int main()
{             
    FILE **a = &meyersSingleton<FILE*>::instance();
    *a = fopen("coeff", "rb");
    read_file();   
    return 0;
}
这不是一个非常直观的解决方案,但它可以保证您只有一个全局和单个 FILE。
如果您需要更多单个文件,您可以再添加一个模板参数
template<typename T, size_t N = 0>
class meyersSingleton
{
public:
  static T& instance()
  {
    static T theSingleton;
    return theSingleton;
  }
  meyersSingleton() = delete;
  ~meyersSingleton() = delete;
  meyersSingleton(meyersSingleton const&) = delete;
  meyersSingleton& operator=(meyersSingleton const&) = delete;
};
如果您使用的是 c,则只需省略此解决方案。
编辑:在大多数情况下,单例被认为是一个糟糕的解决方案,一种不应该使用的反模式,不要管它。这里有一些讨论单例优缺点的好文章。
不要误会我的意思,单例确实解决了一个问题——它保证你一次只会有一个对象(变量、资源等),有时这非常有用(尽管很少见)。日志就是一个例子,我们到处都需要日志,而日志不会在我们的程序中写入任何内容。