我再一次在这里寻求支持。
例如,我有一个名为fp的fopen东西
FILE * fp;
fp=fopen("Entity.dat","wb");我有x个函数,并且需要在所有的函数中使用它,所以问题是我如何才能使它成为公共/全局作用域。
发布于 2013-04-23 00:13:37
您应该使用extern
the_file.h
#ifndef FILE_H
#define FILE_H
...
extern FILE *file;
#endifthe_file.cpp
#include "file.h"
FILE *file;然后打开文件并将句柄存储在file中。接下来,您可以在需要的地方使用file。
发布于 2013-04-23 00:19:37
理想情况下,您应该简单地将其作为参数传递给需要使用它的任何函数:
void func( FILE *f, ... )
{
// do something with f
}
int main( void )
{
FILE *fp = fopen( "Entity.dat", "wb" );
...
func( fp, ... );
...
}发布于 2013-04-23 00:18:34
如果你有选择,请将它作为参数传递,如果你真的没有任何选择,那么你可以考虑单例。
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;
}这不是一个非常直观的解决方案,但它将保证您只有一个全局和单个文件。
如果需要更多单个文件,可以再添加一个模板参数
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,则只需省略此解决方案。
编辑:在大多数情况下,singleton被认为是一个糟糕的解决方案,一个不应该使用的反模式,并把它留在alone.Here是一些讨论singleton利弊的好文章。
why singleton is so bad Singleton I love you, but you're bringing me down
别误会,单例确实解决了一个问题--它保证你一次只有一个对象(变量、资源等等),有时候这很有用(尽管很少见).Log就是一个例子,我们到处都需要日志,而日志不会在我们的程序中写入任何东西。
https://stackoverflow.com/questions/16151709
复制相似问题