考虑这个片段:
#include <iostream>
using std::cout;
using std::endl;
int main()
{
char c[] = {'a','b','c','\0'};
char *pc = c;
char **ppc = &pc;
cout << ppc[0] << endl;
}
这打印abc
作为输出。为什么指向指针的指针的索引char
返回整个字符串?这里,ppc
只指向另一个指向单个指针的指针char
。它如何知道整个字符串以及为什么要返回它?
你必须明白什么std::cout
是以及为什么它治疗char*
作为“字符串”。
开始吧:
std::cout
是一个实例std::ostream
and std::ostream
有很多运营商。这是什么意思?
实施std::ostream
可以,但这里仅作为示例,写法如下:
class ostream
{
// ... a lot more code for constructors and others
ostream& operator <<( const int );
ostream& operator <<( const double );
ostream& operator <<( char* ); <<< this is the implementation you search for!
// a long list of more special overloads follow
};
实现只是简单地输出 char* 指向的“字符串”。
你所看到的只是一个特殊的重载operator<<
为了std::ostream
class.
好的,真正的实现使用非成员重载,但这对于理解如何实现并不重要std::ostream
原则上工作。
欲了解更多详情,请参阅:std::ostream::operator https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt
字符和字符串参数(例如 char 或 const char* 类型)由运算符
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)