【问题标题】:const string doesnt work if appended at the end [duplicate]如果在末尾附加 const 字符串不起作用[重复]
【发布时间】:2012-06-15 20:14:50
【问题描述】:

可能重复:
Concatenate two string literals

为什么这不起作用?

const std::string exclam = "!";          
const std::string message = "Hello" + ", world" + exclam;

但是这很好用

const std::string exclam = "!";       
const std::string message = exclam +
"Hello" + ", world" ;     

请给我解释一下。

谢谢

【问题讨论】:

标签: c++ string


【解决方案1】:

原因是两个字符串字面量相加没有operator+,不需要。如果您只是删除 +,则您的第一个示例有效。

const std::string message = "Hello"  ", world" + exclam;

因为 preprocessor 编译器魔法*) 会将两个相邻的文字加在一起。

第二个例子有效,因为std::string 确实有一个operator+,它添加了一个字符串文字。结果是另一个字符串,可以连接下一个文字。


*) 翻译阶段 6 - 连接相邻的字符串文字标记。

【讨论】:

  • nitpick,字符串连接实际上不是由预处理器完成的,(这意味着不必像我们避免预处理器那样避免它;)
  • 好吧,让那个编译器变魔术。
【解决方案2】:

因为表达式"Hello" + ", world" 不涉及任何std::string,而是两个const char[] 参数。并且没有带有该签名的 operator+。您必须先将其中一个转换为std::string

const std::string message = std::string("Hello") + ", world" + exclam;

【讨论】:

  • 这也可以:const std::string message = "Hello" + (", world" + exclam);
【解决方案3】:

std::string 有一个 + 运算符,这是第二个示例中使用的。 const char * 没有第一个示例中使用的那个运算符。

【讨论】:

    【解决方案4】:

    这取决于关联性。

    第二种情况(从左至右)从std::string 开始评估,它与operator+ 连接。第一种情况以const char * 开头,不存在operator+ 的串联。

    【解决方案5】:

    “如果附加在末尾,const 字符串将不起作用”是一个红鲱鱼。这也不起作用:

    const std::string message = "Hello" + ", world";
    

    这不起作用的原因已在其他答案中进行了解释。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-12
      • 2021-12-16
      • 2022-12-11
      • 2016-11-30
      • 1970-01-01
      • 2016-09-10
      • 2015-11-27
      • 2014-03-06
      相关资源
      最近更新 更多