'+' cannot add two pointers error

前端 未结 3 1266
野性不改
野性不改 2021-01-21 00:14

I can do what the following code shows:

std::string a = \"chicken \";
std::string b = \"nuggets\";
std::string c = a + b;

However, this fails:<

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-21 00:33

    Both "chicken" and "nuggets" has type const char* (as literals in code). So you are trying to add to pointers.

    Try std::string c = std::string("chicken") + "nuggets";

    std::string is not part of language itself, it's a part of standard library. C++ aims to have as few language features as possible. So built-in type for strings is not present in parser etc. That's why string literals will be treaded as pointers.

    EDIT

    To be completely correct: type of literals is really const char[N] (where N is character count in literal +1 for \0. But in C++ arrays ([]) can be treated as pointers, and that is what compiler tries to do (as it cannot add arrays)

提交回复
热议问题