2016-09-23 54 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风格的字符串,这是不可能的。