以下哪approches的最好定義一個全局變量:C++ Singelton類Vs的命名空間與公開靜態變量
- 公共靜態類變量的所有私有變量的類
- 使用單個對象:(單例類)
- 名稱空間 - 我應該只是使用一個名稱空間來代替。
我不確定這個問題是否合理。只是試圖找到最佳做法。
下面的代碼在語法上不正確的,但我認爲它應該傳達的理念:
----------------------------------------------------------------
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生成解析器時。 我需要定義全局變量才能在使用野牛語法時執行操作。
noooooooooooooooooooooooooooooo。 。 。 – 2012-03-28 19:59:08
你在問關於_worst_練習的錯誤問題。 CodeChords說,使用'clientData'。 – Useless 2012-03-28 20:04:46
[C++ FQA](http://www.cs.technion.ac.il/users/yechiel/c++-faq/global-vars.html)[27.15]什麼是使用全局變量的良好編碼標準?這是聲明一個全局變量的理想方法:'// int xyz; ←使這個全球理想的東西是領先的//' ,不要使用全局變量 – 2017-11-02 11:15:50