[英]Get iterator for const reference
我正在开发一个必须使用begin()
方法返回迭代器的类。 另外,我必须开发一个函数来接收这个类的const引用并迭代它。
当我尝试从此方法获取迭代器时,我有以下编译错误: "the object has type qualifiers that are not compatible with the member function."
我无法理解为什么会出现此错误。
这是我写的代码:
// ------------ 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
引用常量对象。 这意味着您只能调用标记为const
。 比如说
class AbstractLayer {
public:
...
virtual const Iterator begin() const = 0; // <- Note use of `const` here
...
};
您的函数接受const AbstractLayer
,这意味着只能在其上调用const
成员函数。 但是, begin
和begin2
不是const
。 实际上,假设只有begin2
返回一个const Iterator
,那么尝试在这个方法中调用begin
是没有意义的。
更改
virtual const Iterator begin2() = 0;
至
virtual const Iterator begin2() const = 0;
和
const Iterator begin2()
至
const Iterator begin2() const
最后,返回一个const Iterator
在你的代码中实际上是没有意义的,因为const
会因为返回rvalue而被丢弃。 无论如何,当你调用begin
时,你不需要执行转换为const Iterator
; 只返回一个Iterator
,编译器会注意使它成为const。
最后,您的Layer
类需要从AbstractLayer
公开派生:
class Layer : public AbstractLayer
你不需要begin
和begin2
。 你需要的是两个版本的begin
- const和non-const。 const one会返回const迭代器。 您还可能需要一个始终返回const迭代器的cbegin
(仅限const)。
在method
, layer
参数是const,它阻止您在其上调用非const方法。 如果通过非const引用( void method(AbstractLayer &layer)
)获取void method(AbstractLayer &layer)
,则可以调用这两个方法。
您应该提供一个const begin
方法,它返回一个const_iterator
以便您可以迭代const AbstractLayer
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.