我是C ++的新手,在使用指向char数组(C样式字符串)的指针时,我对它与ostream对象的行为感到困惑。
const char* items {"sox"};
cout << items << endl;
cout << items[0] << endl;
cout << *items << endl;
cout << &items << endl;
cout << &items[1] << endl;
运行此命令将导致:
sox
s
s
0x7fff2e832870
ox
In contrary to pointer of other data types, printing the variable doesn't output the address, but the string as a whole. By what I understand, this is due to the <<
operator being overloaded for char arrays to treat them as strings.
What I don't understand is, that cout << &items[1]
prints the string from index 1 onward (ox
), instead of the address of the char
at index 1. Is this also due to <<
operator being overloaded or what is the reason for this behavior?
items[1]
is the second character of the array and its address, i.e.&items[1]
, is a pointer to the second character (with index 1) as well. So, with the same rule that you have mentioned foroperator <<
, the second character of the string till the end is printed.The type of
&items[1]
ischar *
. Therefore theconst char *
overload ofoperator <<
is used, which prints the string from index 1 onwards.OTOH, the type of
&items
isstd::string *
, for which no specific overload exists, so the address of the string variable itself is printed.