2016-09-23 87 views
-2

我想寫一個F打開聲明是這樣的:無效的操作數+

FILE *fp; 
fp = fopen("client." + receiver->get_identifier().c_str() + ".vol", "a+"); 

其中接收器 - > get_identifier()返回一個字符串。但是,我在標題中遇到錯誤。我讀了here的問題,但沒有任何運氣,因爲fopen的第一個參數是const char *。我需要改變什麼才能編譯?

+0

Dupe of [this](http://stackoverflow.com/questions/23936246/error-invalid-operands-of-types-const-char-35-and-const-char-2-to-binar)但真的只是一個錯字。擺脫'.c_str'並在()中包裝整個事物,然後使用'.c_str()'。 – NathanOliver

回答

3
receiver->get_identifier().c_str() 

返回const char*,不是std::string,所以operator+不能踢在(它的一個參數必須是std::string)。卸下c_str()並在年底將與std::string::c_str()應該做的伎倆

fopen(("client." + receiver->get_identifier() + ".vol").c_str(), "a+"); 

這是因爲你有一個const char*加上std::string,並且operator+會工作。

如果您可能想知道爲什麼不能爲const char*定義operator+,這是因爲C++不允許運算符重載基本類型;至少一個參數必須是用戶定義的類型。

2

嘗試改變的第一個參數

(string("client.") + receiver->get_identifier() + ".vol").c_str() 

這將添加std::string對象與C-風格串,which can be done,並且僅取字符指針在結束(通過.c_str())。您的代碼現在嘗試添加C風格的字符串,這是不可能的。