为什么在C ++中不允许连接两个const char *?

时间:2017-07-11 04:23:42

标签: c++ string

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

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

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

3 个答案:

答案 0 :(得分:10)

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

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

是允许的,与

相同
 std::string s="helloworld"; 

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

这是编译过程的phase 6。相邻的string literals被连接起来。

顺便说一句,这只适用于字符串文字。 E.g。

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

并且如果实现了这样的+,则需要分配堆内存(在运行时)àlastrdup,并且您需要确定是谁以及何时delete[]free - d。顺便说一句,作为r0ng answered,您无法在指针类型上定义operator +。所以标准委员会决定不允许这样做是明智的。

但是,如果您使用char*std::string替换为两次,则可以正常工作。

答案 1 :(得分:2)

&#34;你好&#34;和#34;世界&#34;有两个auth0指针。没有可用于连接两个const char指针的函数。

您可以尝试以下操作:

const char

答案 2 :(得分:1)

首先,让我们看看std::string("hello") + "world"的工作原理。 在std :: string类中,它有一个成员函数,它会重载&#39; +&#39; operator see the string operators

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

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

char是c / c ++中的原始类型,这意味着不是char类型中的成员函数。因此char本身没有成员函数来重载+运算符。

如果您要重载操作,则必须遵循以下规则:
&#34; 当运算符出现在表达式中时,其操作数中至少有一个具有类类型或枚举类型&#34; reference is here。 char不是一个&#39;类&#39;也不是&#39;枚举类型&#39;。

因此,人们无法像以下那样创建运算符:
const char* operator +(const char* lhs, const char* rhs)

这就是你不能拥有&#34;你好&#34; +&#34;世界&#34;工作