![](/img/trans.png)
[英]error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(int&)’
[英]c++ error: no matching function for call to ‘std::__cxx11::basic_string<char>::append<int>(int, int)’
试图运行这个:
// 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 上运行代码,但出现相同的错误。
您需要先将0x2E
(整数)转换为 char: char(0x2E)
。
str.append<int>(5,char(0x2E));
有没有变异的std::string::append()
它有两个整数-你应该做的第二个参数的字符,因为有一个变种,需要一个整数和字符。
此外,通过使用<int>
,您将模板化字符类型charT
为整数而不是字符,这可能不会按您期望的方式工作。 std::string
通常定义为std::basic_string<char>
因此附加.append<int>
最多会对底层内存产生奇怪的影响。
由于您想再添加五个.
字符,我不知道你为什么不这样做:
str.append(5, '.');
当标准模板库出现问题时,您可以随时查看您正在使用的函数的 C++ 参考: http : //www.cplusplus.com/reference/string/string/append/
在这种情况下,没有任何理由指定 after 追加:执行此操作时,两个参数都被解释为 int,而您希望将第二个参数解释为 char。 您可以通过执行str.append(5,0x2E);
. 您的编译器将搜索最接近的匹配函数,即string& append (size_t n, char c);
并将第二个参数隐式转换为字符。
你只是不需要<int>
部分。 str.append(5, 0x2E);
编译正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.