【发布时间】:2012-04-12 11:15:12
【问题描述】:
以下哪种方法最适合定义全局变量:
- 公共静态类变量
- 将类的单个对象与所有私有变量一起使用:(单例类)
- 命名空间 - 我是否应该只使用命名空间。
我不确定这个问题是否有意义。只是试图找到最佳做法。
下面的代码在语法上不正确,但我认为它应该传达这个想法:
----------------------------------------------------------------
class Reader {
Reader();
Library* lib;
static Reader* reader;
public:
Reader* Instance () {
if (!reader) { reader = new Reader() }
return reader;
}
void setLibrary ( Library* ptr ) { lib = ptr }
Library* getLibrary { return lib }
}
Reader* Reader::reader = NULL;
int main( ) {
...
Library* lib = new Library("test");
Reader::Instance()->setLibrary(lib);
Reader::Instance()->getLibrary()->addCell("AND2X1");
}
-------------- OR -------------
class Reader {
Reader();
public:
static Library* lib;
}
Library* Reader::lib = NULL;
int main( ) {
...
Reader::lib = new Library("test");
Reader::lib->addCell("AND2X1");
}
---------------- OR -----------------
namespace Reader {
Library* lib = NULL;
}
int main( ) {
...
Reader::lib = new Library("test");
Reader::lib->addCell("AND2X1");
}
---------------------------------------------------------------
我正在尝试使用 Tcl_createCommand 在带有 TCL 前端的 C++ 程序中创建新命令。我无法将任何新参数传递给函数实现 因此,我需要全局变量来访问函数内的一些数据。 我为此找到的所有解决方案似乎都在使用全局变量。
我需要上述内容的另一个实例是使用 bison 生成解析器时。 使用野牛语法时,我需要定义全局变量来执行操作。
【问题讨论】:
-
nooooooooooooooooooooooooooooo 。 . .
-
你问错了问题,关于 worst 的做法。正如 CodeChords 所说,使用
clientData。 -
C++ FQA [27.15] 使用全局变量的良好编码标准是什么?以下是声明全局变量的理想方式:
// int xyz; ←the thing that makes this global ideal is the leading //如,不要使用全局变量
标签: c++ static namespaces tcl bison