繁体   English   中英

二进制“ operator +”类型为“ const char [8]”和“ const char *”类型的无效操作数

[英]Invalid operands of types ‘const char [8]’ and ‘const char*’ to binary ‘operator+

我试图写这样的Fopen语句:

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

其中receiver-> get_identifier()返回一个字符串。 但是,标题出现错误。 我在这里阅读了问题但没有运气,因为fopen的第一个参数是const char *。 我必须更改什么才能使其编译?

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 ++不允许对基本类型进行运算符重载。 至少一个参数必须是用户定义的类型。

尝试将第一个参数更改为

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

这将添加带有C样式字符串的std::string对象, 这可以完成 ,并且仅在末尾使用字符指针(通过.c_str() )。 您的代码现在尝试添加C样式字符串,这是不可能的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM