2013-04-17 55 views
1

我創建了一個指向特定目錄的#define。那麼我想結合使用這個定義用於字符串:在C++中使用文字串混合DEFINEs

#define PATH_RESOURCES "/path/to/resources/" 
std::ifstream datafile(PATH_RESOURCES + "textures.dat"); 

然而,編譯器抱怨將使用+運算符字符類型:

error: invalid operands of types ‘const char [11]’ and ‘const char [13]’ to binary ‘operator+’


所以,我怎麼能結合一個帶字符串文字的#define?或者,有沒有更好的方法來完成這一切?我想,使用const變量將是一種替代方案,但這意味着必須傳遞另一個參數,我寧願將它作爲全局定義來保存。

回答

5

你可以寫他們一前一後,沒有+加上他們之間的合併兩個字符串文字:

std::ifstream datafile(PATH_RESOURCES "textures.dat"); 

的字符串文字的一個恰好通過預處理器定義沒有太大改變的事實:你也可以這樣做:

std::ifstream datafile(PATH_"/path/to/resources/" "textures.dat"); 

這是一個demo on ideone

+0

謝謝,這工作。我不知道字符串文字可以像這樣組合。 –

2

嘗試

std::ifstream datafile(PATH_RESOURCES "textures.dat"); 

兩個字符串字面相鄰串連。

2

使用std::ifstream datafile(PATH_RESOURCES "textures.data");

注缺乏+運營商。

你也可以做

std::ifstream datafile(std::string(PATH_RESOURCES) + std::string("textures.data"));如果你真的想要的。

0

創建一個std :: string,爲其指定#define字符串並添加第二個文字。之後使用字符串。

std::string str(PATH_RESOURCES); 
str = str + "textures.dat"; 
std::ifstream datafile(str);