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.
Here is the code that I have written:
// ------------ 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();
}
// -------------------------------------------------------------
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
...
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With