Use base class iterator in a derived class with a template

To tell the truth, I am still a newbie in C++. So I decided to take a evening and do a quick exercise. What I am trying to do is to write a class which uses the iterator from its ‘parent’ class:

 1: #include <vector>
 2: #include <iostream>
 3:  
 4: template <typename T>
 5: class myVector : public std::vector<T>
 6: {
 7: public:
 8:  void Test();
 9: };
 10:  
 11: template <typename T>
 12: void myVector<T>::Test()
 13: {
 14:  typename std::vector<T>::iterator i;
 15:  
 16:  for (i = this->begin(); i != this->end(); i++)
 17:  std::cout << *i << std::endl;
 18:  
 19:  return;
 20: }
 21:  
 22: int main()
 23: {
 24:  myVector<int> v;
 25:  v.push_back(1);
 26:  v.push_back(2);
 27:  v.push_back(3);
 28:  v.push_back(4);
 29:  v.Test();
 30:  return 0;
 31: }
 

The whole point here is the typename in line 14. That is the tricky part which took me a while to figure out. Without it the code won’t even compile. Now I can add all different kinds of sorting methods to myVector. Yes, I know it’s a bad idea. Just code for fun.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注