ostream cout and char *

柔情痞子 提交于 2019-12-31 05:11:31

问题


I have an array of chars like this one:

char arr[3]="hi";
cout << arr;// this will print out hi

So is the operator<< has an overloaded version that takes an ostream object and char *. so cout<<arr; first arr will decays to a chat * . and then operator<<() will print out what the char pointer is pointing to until it find a null-character ?

The same question for cin>>arr; how does it work with operator>> that takes an array as the second operand.


回答1:


Your ostream and istream do have operator<< and operator>> overloaded to take a char*, and arrays decay into pointers to the first element. So, yes it does what you say it does.




回答2:


Exactly in the same way as cout works.

The array arr decays into pointer type, and there exists an overloaded version of istream as well which takes char* as argument. So arr gets passed to the operator>> as char* after decaying.




回答3:


Please see here for details on cout: Standard output stream. Whilst in this page, please click and see the link that says "ostream::operator<<" Likewise see here for details on cin: Standard input stream. Whilst here, please click and see the link that says "operator (>>)"



来源:https://stackoverflow.com/questions/10285753/ostream-cout-and-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!