在C++中:如果我们在字符串中添加一些整数,为什么它从一开始就删除了那个字符数?(string + int)

rev*_*_ss 3 c++ string int add 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;
}
Run Code Online (Sandbox Code Playgroud)

预期输出:Hello World2

实际产出:llo World

PS:要打印"HelloWorld2",我还可以编写cout <<"Hello World"<< i

Som*_*ken 6

"Hello World"不是std::string,它是一个字符串文字所以它的类型是const char[].当你在i这里添加一个整数时,你实际上是在创建一个临时的const char*,首先指向第一个元素const char[]是'H',然后你移动它2个点(因为i是2)所以它指向'l ',然后你传递指针cout,从而cout从'l'开始打印.对这些类型执行二进制运算称为指针运算.

为了更好地理解使用示例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.
Run Code Online (Sandbox Code Playgroud)

请注意,如果您尝试过多地"移动"指针,使其指向字符串中的某些内容,然后尝试访问此指针,则会获得未定义的行为.与访问数组越界的方法相同的是UB.请确保index < size.