为什么C++中不允许连接两个常量字符*?

Why concatenation of two const char* is not allowed in C++?

本文关键字:两个 常量 字符 C++ 不允许 连接 为什么      更新时间:2023-10-16

我尝试了以下内容,但不起作用。为什么?

std::string s = "hello" + "world"; 

为什么C++标准库开发人员决定不重载operator+来实现char*级联?难道不会让人们的生活更简单吗?

使用两个文字字符串,您可以连接它们,但不需要任何运算符,只需要(可选(空格。所以

std::string s="hello" "world"; 

是允许的,并且与

std::string s="helloworld"; 

实际上,在解析时,两个文字字符串粘合在一起。这也适用于 C,发生在预处理扩展之后。

这是编译过程的第 6 阶段。相邻的字符串文本是串联的。

顺便说一句,这仅适用于字符串文字。

例如
std::string s1= ((1<2)?"hello":"goodbye") "world"; // wrong
std::string s2= ("ab")"cd"; // wrong

都错了。

您也可以使用operator ""s

using std::literals::string_literals;
std::string s= "abcd"s + "ef"s;

但是"abcd"s"ef"s都表示一些常数std::string-s,+适用于这些。

为什么 C++ 标准库开发人员决定不重新加载 "+" 来实现 char* 串联?

然后你会想要编码

char* foo = (rand()%4)?"lucky":"unlucky";
char* bar = foo + "xy";  // wrong

如果实现了这样的+,它将需要像strdup一样分配堆内存(在运行时(,并且您需要决定谁以及何时delete[]free-d。 顺便说一句,正如 r0ng 回答的那样,您无法在指针类型上定义operator +。因此,标准委员会不允许这样做的决定是理智的。

但是,如果您将上述char*替换为std::string则有效。

">

hello"和"world"是两个const char指针。没有可用于连接两个const char指针的函数。

您可以尝试以下操作:

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

首先,让我们看看为什么std::string("hello") + "world"有效。 在 std::string 类中,它有一个成员函数,该函数重载了"+"运算符,请参阅字符串运算符

string operator + (const string& lhs, const char* rhs);


std::string("hello") + "world"等同于从 std::string:
调用成员函数operator + (std::string("hello"), "world")

char 是 C/C++ 中的基元类型,这意味着不是 char 类型中的成员函数。所以 char 本身没有成员函数来重载 + 运算符。

如果要重载操作,则必须遵循以下规则:">
当运算符出现在表达式中,并且其至少一个操作数具有类类型或枚举类型时">参考位于此处。char 既不是"类"也不是"枚举类型"。

因此,人们无法创建这样的运算符:
const char* operator +(const char* lhs, const char* rhs)

这就是你不能让"你好"+"世界"工作的原因。