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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.