关于c ++:如何在模板类的内部类中编写虚函数?

How to write virtual function in inner class of template class?

我有一个模板类linearLinkedList的内部类myIterator,我想重写从simpleIterator继承的虚拟方法,但是编译器拒绝它们,因为"模板可能不是虚拟的。"基于这个问题,尽管看起来这是可能的,因为它只取决于类的类型。例如,下面我的代码中的方法foo是合法的。如何实现内部类的虚函数?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
template <class T>
class linearLinkedList
{
public:
...
virtual void foo(T data); //OK
simpleIterator<T> * iterator();
private:
...
class myIterator : public simpleIterator<T>
{
  public:
    myIterator(node<T> ** head);
    virtual ~myIterator(); //inherited from simpleIterator; error when implemented
  private:
    node<T> ** prev;
    node<T> ** next;
    //functions inherited from simpleIterator<T>:
    virtual bool hasNext_impl(); //error when implemented
    virtual T next_impl();
    virtual void remove_impl();
};
...
template<class T>
virtual linearLinkedList<T>::myIterator::~myIterator() { ... }
->
linearLinkedList.h:213:1: error: templates may not be avirtuala
virtual linearLinkedList<T>::myIterator::~myIterator()


不是函数模板本身的成员函数可以标记为virtual,即使它是类模板的一部分,但是:

§7.1.2[DCL.FCT.规范]/P1:

Function-specifiers can be used only in function declarations.

1
2
3
4
function-specifier:
    inline
    virtual
    explicit

The virtual specifier shall be used only in the initial declaration of a non-static class member function; see 10.3.

也就是说,应该从类外定义中删除一个virtual关键字:

1
2
3
template<class T>
virtual linearLinkedList<T>::myIterator::~myIterator() { ... }
~~~~~~^ to be removed