2

If I have a C++ function that takes a string parameter:

void somefunc(const std::string &s)
{
  std::cout << ": " << s << std::endl;
}

If I then have something like:

const char *s = "This is a test...";
somefunc(s + "test");

I get an error:

error: invalid operands of types ‘const char*’ and ‘const char [5]’ to binary ‘operator+’

How can I call somefunc with s plus some other string?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Scott Deagan
  • 331
  • 3
  • 8

1 Answers1

4

Pointers (const char*) can't be added by operator+.

You can make either operand to std::string, to concatenate strings.

somefunc(std::string(s) + "test");
somefunc(s + std::string("test"));

Or use std::string literal.

using namespace std::string_literals;
somefun(s + "test"s);
//          ^^^^^^^  <- std::string, not const char[5]
songyuanyao
  • 169,198
  • 16
  • 310
  • 405