简体   繁体   English

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

[英]Range-for loop recognizes wrong type (C2440)

The C2440 error (cannot convert from 'char' to 'Text_iterator' is occurring on this line): C2440错误(此行上无法从'char'转换为'Text_iterator'):

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

Replacing 'Text_iterator' with 'auto' gives the 'illegal indirection' error (dereferenced type must be a pointer). 将'Text_iterator'替换为'auto'会出现“非法间接”错误(取消引用的类型必须是指针)。

Class Document has begin() and end() functions defined (returning Text_iterator), and Text_iterator has the usual iterator operators. 类Document定义了begin()和end()函数(返回Text_iterator),而Text_iterator具有常规的迭代器运算符。 Here is the code: 这是代码:

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

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

    // . . .
};

And Document: 和文件:

struct Document
{
    list<Line> line;

    Text_iterator begin()
    {
        // . . .
    }

    Text_iterator end()
    {
        // . . .
    }

    // . . .
};

You are using the incorrect type for the loop variable. 您为循环变量使用了错误的类型。 The variable is not the iterator of the container but it is what the iterator of that container points to. 变量不是容器的迭代器,而是该容器的迭代器指向的对象。

If you had 如果你有

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

And you want to use a ranged based for loop you would use 而且您想使用基于范围的for循环

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

You would not use 你不会用

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

So you need to use whatever Text_iterator points to instead of Text_iterator . 因此,您需要使用Text_iterator指向的内容而不是Text_iterator In this case 在这种情况下

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;
}

should work. 应该管用。

The range-for iterates over the content of a container. range- 用于对容器的内容进行迭代。 So it's not about iterators, but dereferenced iterators. 因此,它与迭代器无关,而与取消引用的迭代器有关。

Your code should be: 您的代码应为:

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

or if you really want to keep control over the iterators: 或者,如果您真的想控制迭代器,请执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM