我很好奇复合赋值运算符是否对多个参数有效。我的猜测是 += 不会有副作用,但可能与“-=”的情况不同。
std::string a;
a += "Hello" + " "+"World"; // doesn't compile
std::string name = "Old";
a += "Hello" + name +"World"; // compiles
最佳答案
这不是一个有效的表达式,因为没有用于字符串文字的运算符 +
"Hello" + " "+"World
(更准确地说是指针,因为在表达式中,除了极少数异常(exception),字符串文字会转换为指向其第一个符号的指针。)
你可以这样写
std::string a;
( ( a += "Hello" ) += " " ) += "World";
但是如果写的话可读性会更好
a += "Hello";
a += " ";
a += "World";
或者正如 @Bathsheba 在对我的回答的(有值(value)的)评论中指出的那样,您可以通过以下方式使用用户定义的字符串文字
#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";
然后可以使用为类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';
}
请注意,每个运算符都会返回一个 std::basic_string
类型的对象,为其定义了 operator +
。也就是说,在运算符的每次调用中,都存在一个类型为 std::basic_string
的对象作为参数。
关于c++ - 这个字符串加法是一个有效的表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56044454/