为什么C++中不允许连接两个常量字符*?
Why concatenation of two const char* is not allowed in C++?
我尝试了以下内容,但不起作用。为什么?
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)
这就是你不能让"你好"+"世界"工作的原因。
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 在声明中合并两个常量"std::set"(不是在运行时)
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- 常量shared_ptr:我需要两个还是只需要一个
- 我可以写出小于 -0.5 两个 ulps 的常量表达式双精度吗?
- 为什么C++中不允许连接两个常量字符*?
- 两个指针之间的差异是合法的 c++17 常量表达式
- 将指针 (T*) 强制转换或转换为两个常量 (T 常量 * 常量) 指针
- C/C++签名中两个常量的含义
- 检查两个常量是否为空
- 将两个常量char*组合在一起
- 带有两个常量的C++:pow()优化
- 为什么比较 constexpr 函数的两个参数不是静态断言的常量条件
- 比较从函数返回的两个std::string常量(两个json精神get_str())1-liner
- 具有相同元素的两个常量缓冲区