简体   繁体   English

如何定义来自非模板基类的成员函数

[英]How to define member function coming from non-template base class

I have a non-templated abstract base class. 我有一个非模板的抽象基类。 How do I define the pure virtual function outside derived class? 如何在派生类之外定义纯虚函数?

    #include <iostream>

    class base {
         public:
         virtual void func() = 0;
    };

    template<typename T>
    class der : public base{
    };

    template<typename T>
    void der<T>::func()
    {
         std::cout<<"In Der";
    }

The following error comes up: 出现以下错误:

template.cpp:13: error: no ‘void der<T>::func()’ member function declared in class ‘der<T>’
template.cpp:13: error: template definition of non-template ‘void der<T>::func()’

Declare the member function. 声明成员函数。

template<typename T>
    class der : public base{
    public:
        void func();
    };

There's no automatic declaration of member functions that you may or may not wish to override in a derived class - you have to explicitly declare and define these. 没有自动声明的成员函数,您可能希望或不希望在派生类中重写这些成员函数-您必须显式声明和定义这些成员函数。 Whether the derived class is implemented as a template or not doesn't matter for this. 派生类是否实现为模板对此无关紧要。

You must declare the virtual override in the derived class definition. 您必须在派生类定义中声明虚拟替代。

template <typename T>
class der : public base {
public:
    virtual void func();
};

This will work: 这将起作用:

#include <iostream>

class base {
     public:
     virtual void func() = 0;
};

template<typename T>
class der : public base{
  public:
  void func()
  {
       std::cout<<"In Der";
  }
};

It has been recommended to me to drop function definitions straight into templates when possible, except for specializations. 我建议我尽可能将函数定义直接放入模板中,专业化除外。

edit: 'inline' was not the best choice of word here 编辑: “内联”不是此处单词的最佳选择

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

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