大家想必在很多场景下需要打印输出指针地址。看一下下面的输出:
CObject
*
pObject
=
new
CObject
;
std
::
cout
<<
pObject
<<
std
::
endl
;
这样直接打印出指针的pObjedct地址。但是下面的输出
char
*
ptr
=
"abc"
;
std
::
cout
<<
ptr
<<
std
::
endl
;
直接输出字符串:"abc",这是为什么?稍等片刻。
void
*
pVoid
=
ptr
;
std
::
cout
<<
pVoid
<<
std
::
endl
;
这样就可以直接输出指针地址。
想必疑问为何这样的显现呢?其实都是因为
operator
<< 重载导致的行为。
std::cout 是 std::ostream 的一个对象而已,在ostream 的实现中,
对字符串指针进行了全局函数重载处理,VS2008中实现原型:
template
<
class
_Traits
>
inline
basic_ostream
<
char
,
_Traits
>&
__CLRCALL_OR_CDECL
operator
<<
(
basic_ostream
<
char
,
_Traits
>&
_Ostr
,
const
char
*
_Val
)
其它打印指针则:ostream 成员函数:
_Myt
&
__CLR_OR_THIS_CALL
operator
<<(
const
void
*
_Val
)
CObject
*
pObject 则隐式转换打印输出指针指向的地址