Can't add strings in C++

前端 未结 7 1970
陌清茗
陌清茗 2020-12-24 14:13
#include 


int main()
{
    const std::string exclam = \"!\";
    const std::string message = \"Hello\" + \", world\" + exclam;
    std::cout <&l         


        
相关标签:
7条回答
  • 2020-12-24 15:04

    C-style string literals ("Hello" and ", world") are equivalent to anonymous arrays:

    static const char anon1[6] = { 'H', 'e', 'l', 'l', 'o', '\0' };
    static const char anon2[8] = { ',', ' ', 'w', 'o', 'r', 'l', 'd', '\0' };
    

    ...so when you type "Hello" + ", world", you're trying to add two arrays anon1 + anon2 which is not an operation that C or C++ supports.

    Remember, string literals in C/C++ are just arrays (or addresses of arrays). You have to use a string class (e.g. std:string) in order to use operators like +.

    0 讨论(0)
提交回复
热议问题