2016-04-03 12 views
1

ウェブサイトはconst char * foo = "hello";を言うと、我々はそれが文字列リテラルのアドレスを返す出力FOOを行うとき、私は自宅でこれを試してみましたが、私は"hello"を取得し、私は*fooを行うとき、私はまた"hello"を取得し、私の質問は、ウェブサイトが間違っている?はcplusplus.comが間違っていますか?ポインタと文字列リテラル<a href="http://www.cplusplus.com/doc/tutorial/pointers/" rel="nofollow">this page "Pointers and string literals" section</a>で

enter image description here

+1

どうやって出力していますか? 'char'へのポインタを出力するときに記述するように、いくつかの出力メソッドが必要です(つまり、アドレス自体ではなくアドレスに何が出力されているか)。 – Peter

+0

私はcout << fooを行い、helloを与えました。演算子<< overloaded – szd116

+0

@ szd116 'cout << static_cast (foo);はポインタの値、つまりポインタが指すアドレスを出力します。 'operator <<'は 'char *'のためにオーバーロードされ、Cスタイルの文字列として扱われます。 – songyuanyao

答えて

1

次のコードは、すべてを説明しています。

const char *foo = "hello"; 
cout << static_cast<const void *>(foo) << endl; //result is address of "hello" 
cout << foo << endl; //result is "hello" 
cout << *foo << endl; // result is 'h' 

cout << static_cast<const void *>(foo)は、以下の機能を呼び出す。

_Myt& __CLR_OR_THIS_CALL operator<<(const void *_Val) 

cout << fooは、以下の機能を呼び出す。

template<class _Traits> inline 
    basic_ostream<char, _Traits>& operator<<(
     basic_ostream<char, _Traits>& _Ostr, 
     const char *_Val) 

cout << *fooは、以下の機能を呼び出す。

template<class _Traits> inline 
    basic_ostream<char, _Traits>& operator<<(
     basic_ostream<char, _Traits>& _Ostr, char _Ch) 

上記の関数の最後のパラメータに注意してください。
次のスナップショットはhttp://www.cplusplus.com/doc/tutorial/pointers/からのものです。内容は間違いありません。 enter image description here

+0

ありがとう、今私は理解する – szd116

関連する問題