亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么將char指針流傳輸到cout不能打印地址?

為什么將char指針流傳輸到cout不能打印地址?

C++
紫衣仙女 2019-12-06 15:47:08
當我使用來打印char指針時printf(),它使用轉換說明符來決定是否應打印地址或根據%u或%s來打印整個字符串。但是當我想使用相同的方法時cout,如何cout決定在地址和整個字符串之間應該打印什么呢?這是一個示例源:int main(){  char ch='a';  char *cptr=&ch;  cout<<cptr<<endl;  return 0;}在這里,在我的GNU編譯器中,cout正在嘗試將ch輸出為字符串。我如何獲得ch通過cptr使用的地址cout?
查看完整描述

3 回答

?
MMTTMM

TA貢獻1869條經驗 獲得超4個贊

重載分辨率選擇ostream& operator<<(ostream& o, const char *c);用于打印C樣式字符串的。您要ostream& operator<<(ostream& o, const void *p);選擇另一個。您可能最好在這里進行演員表:


 cout << static_cast<void *>(cptr) << endl;


查看完整回答
反對 回復 2019-12-06
?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

cout如果收到一個字符串,則打印一個字符串,就這么char *簡單。


下面是重載operator <<的ostream:


ostream& operator<< (bool val);

ostream& operator<< (short val);

ostream& operator<< (unsigned short val);

ostream& operator<< (int val);

ostream& operator<< (unsigned int val);

ostream& operator<< (long val);

ostream& operator<< (unsigned long val);

ostream& operator<< (float val);

ostream& operator<< (double val);

ostream& operator<< (long double val);

ostream& operator<< (const void* val);


ostream& operator<< (streambuf* sb);


ostream& operator<< (ostream& ( *pf )(ostream&));

ostream& operator<< (ios& ( *pf )(ios&));

ostream& operator<< (ios_base& ( *pf )(ios_base&));


ostream& operator<< (ostream& out, char c );

ostream& operator<< (ostream& out, signed char c );

ostream& operator<< (ostream& out, unsigned char c );



//this is called

ostream& operator<< (ostream& out, const char* s );

ostream& operator<< (ostream& out, const signed char* s );

ostream& operator<< (ostream& out, const unsigned char* s );

如果需要地址,則需要:


ostream& operator<< (const void* val);

因此您需要轉換為const void*。


查看完整回答
反對 回復 2019-12-06
?
小唯快跑啊

TA貢獻1863條經驗 獲得超2個贊

我只是將其轉換為void *,因此它不會嘗試將其解釋為C字符串:


cout << (void*) cptr << endl;

但是,一個更安全的選擇是使用dirkgently的答案中的static_cast(這樣,至少在編譯時檢查了強制類型轉換)。


查看完整回答
反對 回復 2019-12-06
  • 3 回答
  • 0 關注
  • 647 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號