Range-for循环识别错误类型(C2440)

时间:2016-08-01 15:35:32

标签: c++ for-loop syntax stl

C2440错误(无法从' char'转换为' Text_iterator'正在此行中发生):

void print(Document& d)
{
    for (Text_iterator p : d) cout << *p;
}

更换&#39; Text_iterator&#39;用&#39; auto&#39;给出了非法间接&#39;错误(取消引用类型必须是指针)。

Class Document定义了begin()和end()函数(返回Text_iterator),而Text_iterator有通常的迭代器运算符。这是代码:

class Text_iterator
{
    list<Line>::iterator ln;
    Line::iterator pos;
public:
    // . . .

    char& operator*() { return *pos; }
    Text_iterator& operator++();

    // . . .
};

文件:

struct Document
{
    list<Line> line;

    Text_iterator begin()
    {
        // . . .
    }

    Text_iterator end()
    {
        // . . .
    }

    // . . .
};

2 个答案:

答案 0 :(得分:4)

您使用的循环变量类型不正确。变量不是容器的迭代器,但它是该容器的迭代器所指向的。

如果你有

std::vector<int> foo(10);

你想使用一个基于范围的for循环来使用

for (int e : foo) // or for (auto e : foo) 
    std::cout << e << " ";

您不会使用

for (std::vector<int>::iterator e : foo)
    std::cout << *e << " ";

因此,您需要使用Text_iterator点而不是Text_iterator。在这种情况下

void print(Document& d)
{
    // if p is cheap to copy
    for (auto p : d) cout << p;
    // if p is expensive to copy
    for (const auto& p : d) cout << p;
}

应该有用。

答案 1 :(得分:3)

range-for遍历容器的内容。所以它不是关于迭代器,而是取消引用迭代器。

您的代码应为:

void print(Document& d)
{
    for (auto c : d) cout << c;
}

或者如果你真的想要控制迭代器:

void print(Document& d)
{
    for (auto p = d.begin(); p!=d.end(); p++) cout << *p;
}
相关问题