取消引用字符串迭代器无法编译

Dereferencing string iterator won't compile

本文关键字:编译 迭代器 引用 字符串 取消      更新时间:2023-10-16

我遇到了一个问题,示例代码将在代码块环境中编译和运行,但不会在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;

然而,在代码的后面,我还有另外两个取消引用的问题

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

我真的不明白为什么这些错误依赖于编译器。

很抱歉格式化,但我无法让它接受代码。

添加以下include指令:

#include <string>

因为这是定义CCD_ 1的地方。

注意VS2012支持基于范围的for语句,它将把输出循环转换为:

for (auto const& name: names) std::cout << name << std::endl;

ostream operator<<(ostream& os, const string& str)string标头中定义。

你可能只是忘了把它包括在内,才会出现这种错误。

你应该把它放在文件的顶部:

#include <string>

实时示例