添加字符串和文字 (C++)

Adding strings and literals (C++)

在 C++ Primer 一书中,我看到了这样的语句:"When we mix strings and string or character literals, at least one operand to each + operator must be a string type"

我注意到以下内容无效:

#include<string>
int main()
{
    using std::string;
    string welcome = "hello " + "world";    //example 1
    string short_welcome = 'h' + 'w';      //example 2

    return 0;
}

我只是想了解幕后发生的事情。

文字字符串实际上是常量字符数组。因此,它们会衰减为指向其第一个元素的指针。添加两个字符串文字就是添加这些指针。结果是指向一些完全不相关的位置的指针。

对于字符,它们首先得到 promoted to int 然后它们作为整数相加,结果是 int.


对于第一个示例,当您执行 "hello " + "world" 时,实际上等同于 &(("hello ")["world"])。这没有任何意义,添加文字字符串也没有任何意义。

您只能为用户定义的类型重载运算符,例如 class std::string

所以这些运算符用于基本类型

"hello " + "world"

'h' + 'w'

不能超载。

在第一个表达式中,字符串文字被转换为指向其第一个元素的指针。但是二元运算符 + 没有为指针定义。

在第二个表达式中,字符文字被转换为整数,结果是一个整数。但是 class std::string 没有接受整数的隐式构造函数。

你可以这样写

string welcome = std::string( "hello " ) + "world"; 

string welcome = "hello " + std::string( "world" ); 

string short_welcome( 1, 'h' );
short_welcome += 'w';

第一种情况,"hello""world"不是std::strings!按照你写的方式,它们是 char-数组。

克服这个问题的一种方法是将它们显式定义为字符串文字:

string welcome = "hello "s + "world"s;    //example 1

这是 std::string 的一部分,定义为 operator""。但是需要加上using namespace std::string_literals;才能使用

其余的在其他答案中解释。