这个字符串加法是一个有效的表达式吗?

Is this string addition a valid expression?

我很好奇复合赋值运算符是否对多个参数有效。我的猜测是 += 不会有副作用,但可能与“-=”不同。

std::string a; 
a += "Hello" + " "+"World"; // doesn't compile
std::string name = "Old";
a += "Hello" + name +"World"; // compiles

这不是一个有效的表达式,因为没有用于字符串文字的运算符 +

"Hello" + " "+"World

(更准确地说是指针,因为在表达式中,除了极少数例外,字符串文字会转换为指向其第一个符号的指针。)

你可以这样写

std::string a; 
( ( a += "Hello" ) += " " ) += "World";

但是写成

会更易读
a += "Hello";
a += " ";
a += "World";

或者正如 @Bathsheba 在对我的回答的(有价值的)评论中指出的那样,您可以按以下方式使用 user-defined 字符串文字

#include <string>
#include <iostream>

int main()
{
    using namespace std::string_literals;
    std::string a; 
    a += "Hello"s + " " + "World";

    std::cout << a << '\n';
}

至于这个说法

a += "Hello" + name +"World";

然后可以使用为 class std::basic_string

定义的运算符重写
template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator+(const charT* lhs, const basic_string<charT, traits, Allocator>& rhs);

template<class charT, class traits, class Allocator>
basic_string<charT, traits, Allocator>
operator+(basic_string<charT, traits, Allocator>&& lhs, const charT* rhs);

喜欢

a += operator +( operator +( "Hello", name ), "World" ); 

例如

#include <string>
#include <iostream>

int main()
{
    std::string a;
    std::string name = "Old";

    a += operator +( operator +( "Hello ", name ), " World" ); 

    std::cout << a << '\n';
}

考虑到每个运算符 returns 都是定义了 operator + 类型 std::basic_string 的对象。也就是说,在运算符的每次调用中,都存在一个 std::basic_string 类型的对象作为参数。

表达式 a += "Hello" + " " + "World" 分组a += ("Hello" + " " + "World")

右侧是一组 3 个 const char[] 文字。当应用于二进制加法时,这些会衰减为 const char* 指针。由于无法添加指针,因此需要编译器发出诊断。

(请注意,表面上等效的表达式 a = a + "Hello" + " " + "World" 是可编译的。)

复合赋值运算符+=不在其中。

您可以将 +=std::string 一起使用,因为 it defines the relevant overload,但它只有 一个 参数。

并且您已尝试将通过 +ing 多个字符串文字构造的表达式作为该参数传递。这不会编译。

一些替代方案,在这个玩具箱中,可能会激发您的实际情况的解决方案:

选项 1

// Multiple calls to +=
std::string a;
a += "Hello";
a += " ";
a += "World";

选项 2

// String literal concatenation!
std::string a; 
a += "Hello" " " "World";

选项 3

// Repeated std::string concat
std::string a;
a += std::string("Hello") + " " + "World";

选项 4

// Same
using namespace std::string_literals;
std::string a; 
a += "Hello"s + " " + "World";

选项 5

// Don't bother
std::string a;
a += "Hello World";