Can't add strings in C++

前端 未结 7 2005
陌清茗
陌清茗 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:00

    The problem is that basic string literals like "this is a literal" are not of type std::string so they do not concatenate with the + operator.

    In post C++14 you can use standard user defined string literals that are of type std::string:

    using namespace std::literals; // somewhere in the scope
    
    auto message = "Hello"s + ", world"s; // message is type std::string
    

    See std::literals::string_literals::operator""s.

提交回复
热议问题