2
#include <iostream>
using namespace std;
int main() {
    string a = "";
    a += '0' + 1; // got compiled
    a = a + ('0' + 1); // compile error
    return 0;
}

why the second one got a compile error but the first one not?

prog.cc: In function 'int main()':
prog.cc:6:11: error: no match for 'operator+' (operand types are 'std::string' {aka 'std::__cxx11::basic_string<char>'} and 'int')
    6 |     a = a + ('0' + 1); // compile error
      |         ~ ^ ~~~~~~~~~
      |         |        |
      |         |        int
      |         std::string {aka std::__cxx11::basic_string<char>}

I think first '0' + 1 will get integer promotion and turn to type int, then compiler will try to find overloading operator function, trying to implicitly convert int to char.

please help explain in detail what conversion happened, which overload function called, what the compiler does.

thx very much!

jin zhenhui
  • 105
  • 4

0 Answers0