【问题标题】:Invalid operands of types ‘const char [8]’ and ‘const char*’ to binary ‘operator+“const char [8]”和“const char*”类型的无效操作数到二进制“operator+”
【发布时间】:2016-09-23 15:59:25
【问题描述】:

我正在尝试编写这样的 Fopen 语句:

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

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

【问题讨论】:

  • this 的欺骗,但实际上只是一个错字。去掉 .c_str 并将整个东西包装在 () 中,然后使用 .c_str()

标签: c++ fopen


【解决方案1】:
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*s 定义operator+,那是因为C++ 不允许基本类型的运算符重载;至少一个参数必须是用户定义的类型。

【讨论】:

    【解决方案2】:

    尝试将第一个参数更改为

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

    这将添加带有 C 样式字符串 which can be donestd::string 对象,并且仅在末尾获取字符指针(通过 .c_str())。您的代码现在尝试添加 C 样式字符串,这是不可能的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 2014-09-30
      • 1970-01-01
      • 2020-06-23
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多