【问题标题】:c++ error: no matching function for call to ‘std::__cxx11::basic_string<char>::append<int>(int, int)’c++错误:没有匹配函数调用'std::__cxx11::basic_string<char>::append<int>(int, int)'
【发布时间】:2020-07-02 07:48:59
【问题描述】:

尝试运行:

// appending to string
#include <iostream>
#include <string>

int
main()
{
  std::string str;
  std::string str2 = "Writing ";
  std::string str3 = "print 10 and then 5 more";
  // used in the same order as described above:
  str.append(str2);                         // "Writing "
  str.append(str3, 6, 3);                   // "10 "
  str.append("dots are cool", 5);           // "dots "
  str.append("here: ");                     // "here: "
  str.append(10u, '.');                     // ".........."
  str.append(str3.begin() + 8, str3.end()); // " and then 5 more"
  str.append<int>(5, 0x2E);                 // "....."

  std::cout << str << '\n';
  return 0;
}

但是在 str.append(5,0x2E) 上有错误:

错误:没有匹配函数调用'std::__cxx11::basic_string::append(int, int)'

使用 VS Code 1.43.1,在 ubuntu 19.10 上运行,gcc 版本 9.2.1 20191008 (Ubuntu 9.2.1-9ubuntu2)。

我尝试在 Code::Blocks 16.01 IDE 和 windows 上运行代码,但出现了同样的错误。

【问题讨论】:

    标签: c++ compiler-errors int append


    【解决方案1】:

    您需要先将0x2E(整数)转换为字符:char(0x2E)

    str.append<int>(5,char(0x2E));
    

    【讨论】:

      【解决方案2】:

      当标准模板库出现问题时,您可以随时查看您正在使用的函数的 c++ 参考:http://www.cplusplus.com/reference/string/string/append/

      在这种情况下,没有任何理由在追加后指定:这样做时,两个参数都被解释为 int,而您希望第二个参数被解释为 char。您可以通过 str.append(5,0x2E); 简单地实现这一点。您的编译器将搜索最接近的匹配函数 string&amp; append (size_t n, char c); 并将第二个参数隐式转换为 char。

      【讨论】:

      【解决方案3】:

      您只是不需要&lt;int&gt; 部分。 str.append(5, 0x2E); 编译正常。

      【讨论】:

        【解决方案4】:

        no variantstd::string::append() 中的 no variant 接受两个整数 - 您应该将第二个参数设为字符,因为 是一个接受整数和字符的变体。

        此外,通过使用&lt;int&gt;,您可以将模板化字符类型charT 更改为整数而不是字符,这可能不会按您期望的方式工作。 std::string 通常定义为 std::basic_string&lt;char&gt;,因此附加 .append&lt;int&gt; 最多会对底层内存产生奇怪的影响。

        既然您想再添加五个 . 字符,我不确定您为什么不这样做:

        str.append(5, '.');
        

        【讨论】:

        猜你喜欢
        • 2020-07-14
        • 2018-12-05
        • 1970-01-01
        • 1970-01-01
        • 2022-01-13
        • 2020-03-05
        • 2020-12-12
        • 2012-06-18
        • 1970-01-01
        相关资源
        最近更新 更多