【问题标题】:How to write virtual function in inner class of template class?如何在模板类的内部类中编写虚函数?
【发布时间】:2015-10-14 07:08:49
【问题描述】:

我的模板类linearLinkedList<T> 有一个内部类myIterator,我想覆盖从simpleIterator<T> 继承的虚拟方法,但编译器拒绝它们,因为“模板可能不是虚拟的。 "不过,基于this question,这似乎应该是可能的,因为它只取决于类的类型。例如,下面我的代码中的方法foo 是合法的。如何实现内部类的虚函数?

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 âvirtualâ
virtual linearLinkedList<T>::myIterator::~myIterator()

【问题讨论】:

  • 不要将 virtual 关键字放在类外定义中
  • 你不能在类定义之外使用 virtual 关键字。
  • @PiotrSkotnicki 哦,我真傻。想让我接受这个答案吗?

标签: c++ templates inner-classes virtual-functions


【解决方案1】:

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

§ 7.1.2 [dcl.fct.spec]/p1:

函数说明符只能用在函数声明中。

function-specifier:
    inline
    virtual
    explicit

virtual 说明符应仅在非静态类成员函数的初始声明中使用;见 10.3。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-04
    • 2016-02-08
    • 2021-11-08
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多