2011-04-04 44 views
20

我需要在我的C++程序中共享一些字符串。我應該使用#define還是const字符串?感謝const string與#define

mystring1.h

#define str1 "str1" 
#define str2 "str2"  

或者
mystring2.h

extern const string str1; 
extern const string str2; 

mystring.cpp

const string str1 = "str1"; 
const string str2 = "str2"; 
+0

預處理器只能用於包含守衛,'__FILE__'和類似的內置宏,以及#ifdefs用於平臺特定的常量。雖然你可以使用它來定義你的代碼實際使用的常量,但下面的答案指出了幾個原因,這是一個壞主意。 – 2011-04-05 00:38:59

回答

19

推薦第二個選項。如果使用第一個選項(預處理器),則會限制對象的靈活性。

考慮以下...你將不能夠這樣比較字符串:

if (str1 == "some string") 
{ 
    // ... 
} 
+0

但你可以這麼做: 如果(的std :: string(STR1)== 「一些字符串」) { // ... } – traal 2015-04-10 18:50:37

+0

也許一個單獨的問題,而是怎麼樣'常量string' VS'constexpr char []'(因爲constexpr不能用於字符串)? – Zitrax 2016-12-14 10:58:14

2

如果你沒有使用預處理不要」牛逼!

如果在資源編輯器或清單中需要這些字符串,或者您可能必須使用這些字符串。

5

如果是C++,則應該使用C++標準庫的std::string。它比預處理器宏更清晰,它在定義時將在內存中具有單個位置,並且它具有std::string的所有額外功能,而不僅僅是指針比較,與使用預處理器宏創建的隱式const char*一樣。

+1

我使用std :: string – user612308 2011-04-05 00:29:25

+1

對不起,我誤讀'string str1'爲const char []'。你真的應該避免使用名稱空間標準。 – 2011-04-05 00:47:09

1

你也可以只使用恆定的數據,而不是一個字符串對象一個const char *串,因爲對象需要在程序開始時用常量數據進行初始化。如果你不會用字符串做很多事情,只是顯示它們或者按照原樣打印出來,那就這樣做。

所以:

extern const char * str1; 

const char * str1 = "str1"; 
0

我會建議使用的功能。

extern const std::string& str1(); 
extern const std::string& str2(); 

這爲您在.cpp文件中獲取這些字符串的方式提供了更大的靈活性。

0

另請參考Google C++ style guide中所述的非POD靜態構造和破壞順序問題。

一種替代方法是使用:

const char str1[] = "str1"; 
const char str1[] = "str2"; 
2

要利用的C OO優點++,我會說使用結構/類。

頭:

struct Constants { 
    static const string s1; 
    static const string s2; 
}; 

CPP:

const string Constants::s1 = "blah1"; 
const string Constants::s2 = "blah2"; 

要引用:

cout << Constants::s1 << endl; 
0

如果是C++而不是C的,你應該使用一些變量,而不是一個預處理器宏。前者比後者更清晰。此外,如果使用C++ 17,則可以使用內聯變量:

inline const std::string str = "foobar"; 

// constexpr is implicitly inline 
constexpr const char *str = "foobar"; 

這也是比使用extern更清晰,並且可以在只有報頭的API被使用。

相關問題