简体   繁体   中英

c++ error: no matching function for call to ‘std::__cxx11::basic_string<char>::append<int>(int, int)’

Trying to run this:

// 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;
}

But having error on str.append(5,0x2E):

error: no matching function for call to 'std::__cxx11::basic_string::append(int, int)'

Using VS Code 1.43.1, running on ubuntu 19.10, gcc version 9.2.1 20191008 (Ubuntu 9.2.1-9ubuntu2).

I've tried to run the code on Code::Blocks 16.01 IDE, and windows, but had same error.

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

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

There is no variant of std::string::append() that takes two integers - you should make the second parameter a character, as there is a variant that takes an integer and a character.

In addition, by using <int> , you change the templated character type charT into an integer rather than a character, which is probably not going to work the way you expect. A std::string is generally defined as std::basic_string<char> so appending with .append<int> is going to have weird effects on the underlying memory at best.

Since you're wanting to add five more . characters, I'm not sure why you wouldn't just do:

str.append(5, '.');

When having problems with the standard template library, you can always take a look at the c++ reference of the function you're using: http://www.cplusplus.com/reference/string/string/append/

In this case, there isn't any reason to specify the after your append: When doing this, both arguments get interpreted as an int, while you want the second to be interpreted as a char. You can simply achieve this by doing str.append(5,0x2E); . Your compiler will search the closest matching function, which is string& append (size_t n, char c); and implicitly convert the second argument to a char.

You just don't need the <int> part. str.append(5, 0x2E); compiles fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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