我对 C++ 中的字符指针有疑问。每当我们在 C++ 中创建字符指针时:char *p="How are you doing"
, p 应该包含保存值“how are you getting”的内存位置的地址。
但是,我对示例代码和输出感到困惑。为什么cout<<p
返回整个字符串?它应该给出内存地址的值。其次,为什么cout<<*p
只给出字符串的第一个字符?
Code:
#include <iostream>
using namespace std;
int main () {
const char *str = "how are you\n";
int i[]={1,2,3};
cout << str << endl; // << is defined on char *.
cout << i << endl;
cout << *str << endl;
}
OUTPUT:
how are you
0xbfac1eb0
h
如果你想打印地址,那么你必须投射char*
to void*
, as
const char *str = "how are you\n";
cout << (void*) str << endl;
在演员阵容缺席的情况下,cout
sees str
as const char*
(事实上是这样)等等cout
认为您打算打印以 null 结尾的字符串!
想想:如果你愿意的话coud << str
要打印地址,如何打印字符串本身?
--
无论如何,这里有更详细的解释:
operator<<
已超载char*
也void*
:
//first overload : free standing function
basic_ostream<char, _Traits>& operator<<(basic_ostream<char, _Traits>& _Ostr, const char *_Val);
//second overload : a member of basic_ostream<>
_Myt& operator<<(const void *_Val);
在没有强制转换的情况下,第一个重载会被调用,但是当你强制转换为void*
,第二个重载被调用!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)