简体   繁体   English

从STL容器类公开继承时,如何使用迭代器类型?

[英]How do I use the iterator type when inheriting publicly from an STL container class?

I am making a program in which I am inheriting publicly my Set class from a built-in STL container class set . 我正在编写一个程序,在该程序中我从内置STL容器类set公开继承了Set类。 I have to use the iterator type, while making some other specialized functions for my own Set class, as defined in the stl set class. 我必须使用迭代器类型,同时为自己的Set类(在stl set类中定义)创建一些其他专用功能。

Now my question is: What would be the syntax to declare variables of iterator type inside my member functions? 现在我的问题是:在成员函数中声明迭代器类型的变量的语法是什么? I have been trying: 我已经试了:

  template<typename T>
  class Set : public set<T> {
         public:
         bool func()
         {
            iterator it,it2;
         }
   };

But the compiler is not recognizing iterator type. 但是编译器无法识别迭代器类型。 Kindly tell me the syntax to use the iterator type from the stl set class. 请告诉我使用stl set类中的迭代器类型的语法。

The compiler complains because it doesn't know that iterator is in fact a member of set<T> . 编译器抱怨是因为它不知道iterator实际上是set<T>的成员。 set<T> is what's called a dependent type, because it depends on the type parameter T . set<T>是所谓的从属类型,因为它取决于类型参数T In a nutshell, the compiler does not look inside dependent names when resolving types. 简而言之,编译器在解析类型时不会在内部依赖名称中查找。

This FAQ entry is relevant to this question . 此常见问题解答条目与此问题有关 Also, be sure to read through the answers to this Stack Overflow question . 另外,请务必通读此Stack Overflow问题的答案 To fix it, use typename . 要修复它,请使用typename

template<typename T> 
class Set : public set<T> { 
public: 
    bool func() 
    { 
        typename set<T>::iterator it;
        typename set<T>::iterator it2; 
    } 
}; 

But really, you should be using composition instead of inheritnace for this case, like this: 但实际上,在这种情况下,您应该使用composition而不是heritageace ,例如:

template<typename T>
class Set
{
public:
    bool func()
    {
        typename set<T>::iterator it;
        typename set<T>::iterator it2;
    }
private:
    std::set<T> set;
};

You should never ever ever ever ever inherit from an STL container class because the destructors of those classes are not virtual, and so every time you instantiate an instance of your derived class, you'll have a memory leak. 从不应该从STL容器类继承任何东西因为这些类的析构函数不是虚拟的,因此,每次实例化派生类的实例时,都会发生内存泄漏。

As In Silico suggested in one of his comments, give Set a member variable set instead of inheriting from it. 正如In Silico在其评论中建议的那样,请给Set一个成员变量set而不要继承它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM