2017-06-01 74 views
0

你能帮我解释下面的代码的结果吗?结果cout <<“Hello”+ 1 << endl; (C++)

cout<< "Hello" + 1<< endl; 

为什么结果出来为 “ELLO”,我知道打印出Hello1那么我应该使用: COUT < < “你好” < < ENDL; 但谁能帮我解释一下上面代码的顺序: 非常感谢。

+5

'“你好”'是指向的6'char's阵列(未相当,但足够接近)。给这个指针加'1'会产生一个指向下一个'char'的指针,即'e'。那个指针然后被解释为指向一个NUL终止的字符串'“ello”' –

回答

4

你的例子是大致相当于此:

// `p` points to the first character 'H' in an array of 6 characters 
// {'H', 'e', 'l', 'l', 'o', '\0'} forming the string literal. 
const char* p = "Hello"; 
// `q` holds the result of advancing `p` by one element. 
// That is, it points to character 'e' in the same array. 
const char* q = p + 1; 
// The sequence of characters, starting with that pointed by `q` 
// and ending with NUL character, is sent to the standard output. 
// That would be "ello" 
std::cout << q << std::endl; 
+0

非常感谢Igor的解释,我怎样才能接受答案?我在这里看不到Accept按钮。 –

相关问题