获取常量引用的迭代器 [英] Get iterator for const reference
问题描述
我正在开发一个必须使用 begin()
方法返回迭代器的类.此外,我必须开发一个函数来接收此类的 const 引用并对其进行迭代.
I'm developing a class that must return an iterator with the begin()
method. Also, I have to develop a function that receives a const reference of this class and iterates over it.
当我尝试从该方法获取迭代器时,出现以下编译错误:对象具有与成员函数不兼容的类型限定符."
我不明白为什么出现此错误.
When I try to get an iterator from this method, I have the following compilation error: "the object has type qualifiers that are not compatible with the member function."
I can't understand why this error appears.
这是我写的代码:
// ------------ class Neuron -------------
class Neuron { ... };
// ---------------------------------
// ------------ class AbstractLayer -------------
class AbstractLayer {
public:
class Iterator : public std::iterator<std::input_iterator_tag, Neuron> {
public:
Iterator(Neuron *neurons) : _neurons(neurons) {}
private:
Neuron *_neurons;
};
virtual Iterator begin() = 0;
virtual const Iterator begin2() = 0;
};
// ----------------------------------------
// ------------ class Layer -------------
class Layer : AbstractLayer {
public:
Layer(){};
Iterator begin(){ return Iterator(_neurons); }
const Iterator begin2(){ return (const Iterator)begin(); }
private:
Neuron *_neurons;
int _size;
};
// --------------------------------
// ------------ Method where the problem is -------------------
void method(const AbstractLayer &layer){
// Error in both methods:
// "the object has type qualifiers that are not compatible with the member function."
layer.begin();
layer.begin2();
}
// -------------------------------------------------------------
推荐答案
在 method
函数中,layer
引用了一个 constant 对象.这意味着您只能调用标记为 const
的函数.像例如
In the method
function, layer
references a constant object. That means you can only call functions marked as const
. Like e.g.
class AbstractLayer {
public:
...
virtual const Iterator begin() const = 0; // <- Note use of `const` here
...
};
这篇关于获取常量引用的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!