在 C++ 中:如果我们向字符串添加一些整数,为什么它会从开头删除该数量的字符? (字符串+整数)
In C++: If we add some integer to string, why does it removes that number of characters from the beginning? (string + int)
这是我的程序!我想知道这样输出背后的原因。
#include <iostream>
using namespace std;
class A{
public:
void fun(int i){
cout<<"Hello World" + i<<endl;
}
};
int main()
{
A obj1;
obj1.fun(2);
return 0;
}
预期输出:
你好世界2
实际输出:
llo 世界
PS:要打印"HelloWorld2",我也可以编码cout<<"Hello World"<< i
"Hello World" + i
不进行字符串连接。它做指针运算。
它取 C 字符串文字的地址 "Hello World"
,我们称它为 a
。
然后添加到它 a + i
。当 i
大于 c 字符串文字的长度时,取消引用结果指针是未定义的行为。
但是,如果它在范围内,您会在文字中得到一个地址,该地址在打印时将显示为后缀。但是,由于 c 字符串文字是 const
,因此尝试写入该地址再次是 UB。
长话短说,不要这样做。
"Hello World"
被编译为一个字符数组,并作为指向这些字符的指针传递给 operator<<。然后将 i
添加到指针,这会将指针移动到那么多字符上。
"Hello World"
不是 std::string
,它是一个字符串文字,所以它的类型是 const char[]
。当像在 i
中添加一个整数时,您实际上是在创建一个临时的 const char*
,它首先指向 const char[]
的第一个元素,即 'H',然后你将它移动 2 个点(因为 i
是 2)所以它指向 'l',然后你将该指针传递给 cout
因此 cout
从 [=30] 开始打印=].对此类类型进行二元运算称为指针算术。
为了使用示例 char
数组更好地理解,您的代码在幕后类似于:
const char myHello[] = "Hello World";
const char* pointer = myHello; // make pointer point to the start of `myHello`
pointer += i; // move the pointer i spots
cout<< pointer <<endl; // let cout print out the "string" starting at the character pointed to by the new pointer.
请注意,如果您尝试 "move" 指针太多,以至于它指向字符串之外的内容,然后尝试访问该指针,您会得到未定义的行为。与越界访问数组的方式相同是 UB。只要确保 index < size
.
指针运算。
"Hello World"
是字符串文字,由 const char*
.
隐式指向
向指针添加整数 i
会将其向前移动 i positions
(如果 i<0,则向后移动)。
因此"Hello World" + 2
的结果是一个常量指针(const char*
),表示字符串中第三个字母的地址。
这是我的程序!我想知道这样输出背后的原因。
#include <iostream>
using namespace std;
class A{
public:
void fun(int i){
cout<<"Hello World" + i<<endl;
}
};
int main()
{
A obj1;
obj1.fun(2);
return 0;
}
预期输出: 你好世界2
实际输出: llo 世界
PS:要打印"HelloWorld2",我也可以编码cout<<"Hello World"<< i
"Hello World" + i
不进行字符串连接。它做指针运算。
它取 C 字符串文字的地址 "Hello World"
,我们称它为 a
。
然后添加到它 a + i
。当 i
大于 c 字符串文字的长度时,取消引用结果指针是未定义的行为。
但是,如果它在范围内,您会在文字中得到一个地址,该地址在打印时将显示为后缀。但是,由于 c 字符串文字是 const
,因此尝试写入该地址再次是 UB。
长话短说,不要这样做。
"Hello World"
被编译为一个字符数组,并作为指向这些字符的指针传递给 operator<<。然后将 i
添加到指针,这会将指针移动到那么多字符上。
"Hello World"
不是 std::string
,它是一个字符串文字,所以它的类型是 const char[]
。当像在 i
中添加一个整数时,您实际上是在创建一个临时的 const char*
,它首先指向 const char[]
的第一个元素,即 'H',然后你将它移动 2 个点(因为 i
是 2)所以它指向 'l',然后你将该指针传递给 cout
因此 cout
从 [=30] 开始打印=].对此类类型进行二元运算称为指针算术。
为了使用示例 char
数组更好地理解,您的代码在幕后类似于:
const char myHello[] = "Hello World";
const char* pointer = myHello; // make pointer point to the start of `myHello`
pointer += i; // move the pointer i spots
cout<< pointer <<endl; // let cout print out the "string" starting at the character pointed to by the new pointer.
请注意,如果您尝试 "move" 指针太多,以至于它指向字符串之外的内容,然后尝试访问该指针,您会得到未定义的行为。与越界访问数组的方式相同是 UB。只要确保 index < size
.
指针运算。
"Hello World"
是字符串文字,由 const char*
.
向指针添加整数 i
会将其向前移动 i positions
(如果 i<0,则向后移动)。
因此"Hello World" + 2
的结果是一个常量指针(const char*
),表示字符串中第三个字母的地址。