stl - C++ iterator and const_iterator problem for own container class -


I am writing a container class and go into a problem, I can not get my head around Here is a plum bone sample that shows the problem.

There is a container class and two test classes: A test class which uses a study: vector that compiles well and the second test class which is in my own container class in the same way Shows correctly but fails to compile badly.

  #include & lt; Vector & gt; # Include & lt; Algorithm & gt; #include & lt; Iterator & gt; using namespace std; Template & lt; Typename T & gt; Class MyContainer {Public: Class Iterator {Public: typed interpreter self_type; Inline itater () {}}; Square const_iterator {public: typefifference const_iterator self_type; Inline constitutor () {}}; Iterator start () {return iterator (); } Const_iterator start () const {return const_iterator (); }}; // This makes a compiled, std :: vector class TestClassVector {public: zero test ()} {vector & lt; Int & gt; :: const_iterator I = myc.begin (); } Private: Vector & lt; Int & gt; Myc; }; // It fails to make a compilation. Why? Classroom TestClassMyContainer {Public: Zero Test () {MyContainer & lt; Int & gt; :: const_iterator I = myc.begin (); } Private: My Container & lt; Int & gt; Myc; }; Int main (int argc, char ** argv) {return 0; }  

The GCC tells me:

test2.C: member function 'void TestClassMyContainer :: test ()':

Test2.C: 51: Error: Requested conversion from 'MyContainer :: iterator' to non-scalar type 'MyContainer :: const_iterator'

I'm not sure where the compiler is and Why do you want to convert a theater to a setter for your own class, but not for the STL vector class. What am I doing wrong?

When you call, start () is compiler by default Calling non-const starts () . Since myc is not const, it does not make sense to know that instead of using const start () , non-construcance starts () .

There is a Cast operator in the STL iterator which can be converted into a const_iterator silently iterator . If you want to work it then you need to add it:

  square iterator {public: typed inferator self_type; Inline Iterator () {} Operator Constructor () {return const_iterator (); }};  

or const_iterator can be created from a iterator :

  class const_iterator {public : Typedef const_iterator self_type; Const_iterator (Iterator & amp;) {} Inline Controller () {}};  

Comments