2

コード ブロック環境ではサンプル コードがコンパイルおよび実行されるが、Visual Studio 2012 ではコンパイルされないという問題があります。

list<string> names;
names.push_back("Mary");
names.push_back("Zach");
names.push_back("Elizabeth");
list<string>::iterator iter = names.begin();
while (iter != names.end()) {
    cout << *iter << endl;  // This dereference causes compile error C2679
    ++iter;
}

次のコンパイラ エラーが発生します。

1>chapter_a0602.cpp(20): error C2679: binary '<<' : no operator found which takes a
right-hand operand of type 'std::basic_string<_Elem,_Traits,_Alloc>' (or there is no
acceptable conversion)
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>,
1>              _Alloc=std::allocator<char>
1>          ]

文字列のリストを int のリストに変更すると、コードがコンパイルされ、VS2012 で実行されます。

逆参照も次のように変更すると、コンパイルされます

cout << *the_iter->c_str() << endl;

ただし、コードのさらに下に2つの逆参照の問題があります

cout << "first item: " << names.front() << endl;
cout << "last item: "  << names.back() << endl;

これらのエラーがコンパイラに依存する理由が本当にわかりません。

フォーマットについて申し訳ありませんが、コードを受け入れることができませんでした。

4

2 に答える 2

4

次の include ディレクティブを追加します。

#include <string>

operator<<(std::ostream&, std::string&)それが定義されている場所です。

VS2012 は範囲ベースの for ステートメントをサポートしています。これにより、出力ループが次のように変換されます。

for (auto const& name: names) std::cout << name << std::endl;
于 2013-08-21T07:58:19.467 に答える
1

はヘッダーostream operator<<(ostream& os, const string& str)で定義されます。string

この種のエラーが発生するために、それを含めるのを忘れただけでしょう。

ファイルの先頭に含める必要があります。

#include <string>

実例

于 2013-08-21T08:03:24.333 に答える