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

标签 c++ string operator-overloading string-literals user-defined-literals

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

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/

相关文章:

c# - 关于c#中隐式运算符重载的问题

c++ - 是否可以使用 -1 来获取容器/数组的最后一个元素?

c++ - 使用 ./configure 为特定架构构建 .dylib 或 .a 文件

string - 如果 NUL 终止符不在切片的末尾,如何从以 NUL 终止的字节切片中获取 '&str'?

java - 在java中像命令一样实现字符串

java - logback 中的 toString

c++ - 派生赋值运算符从基数调用

c++ - 如何知道来自文本文件的输入是否是 C++ 中的有效数字

c++ - 在二进制表示法中,小数点 "."之后的数字是什么意思?

c++ - 在 C++ 中的不同几何类之间轻松转换?