我有一个名为 Cache 的模板类,它是字符串和对象的 std::map 的容器。
template<class T>
class Cache
{
public:
Cache() {}
virtual ~Cache();
virtual T* loadObject(const char *file);
virtual bool removeObject(const char *file);
virtual void removeAllObjects();
virtual unsigned int getNumObjects() const;
virtual T* getObject(const char *file);
protected:
typedef std::shared_ptr<T> t_ptr;
std::unordered_map<std::string, t_ptr> _objects; //file, shared ptr of object
};
template<class T>
T* Cache<T>::loadObject(const char *file)
{
//if object exists
T *obj = getObject(file);
if(obj)
return obj;
obj = new T();
if(obj)
return _objects.insert(std::make_pair(file,t_ptr(obj))).first->second.get();
else
return nullptr;
}
还有一个继承自 Cache 的模板类称为 ResourceCalled,它基本上是同一个类,但具有不同的 loadObject()
方法。
template<class T>
class ResourceCache : public Cache<T>
{
public:
ResourceCache(ResourceLoader<T> *resourceLoader) : _resourceLoader(resourceLoader)
{}
virtual T* loadObject(const char *file);
private:
ResourceLoader<T> *_resourceLoader;
};
template<class T>
T* ResourceCache<T>::loadObject(const char *file)
{
//if object exists
T *obj = getObject(file);
if(obj)
return obj;
obj = _resourceLoader->load(file);
if(obj)
return _objects.insert(std::make_pair(file,t_ptr(obj))).first->second.get();
else
return nullptr;
}
在我的程序中,我启动 ResourceCache<> 并将 T 设置为一个名为 Mesh 的类,该类在其构造函数中有一个参数。现在,当我尝试编译我的程序时,编译器会提示:
error C2512: 'Mesh' : no appropriate default constructor available
这就像它正在尝试为 Cache 而不是 ResourceCache 构建代码。但是当我在 Cache::loadObject() 之前省略 virtual 关键字时,程序可以编译。
为什么会这样?我学会了在继承时总是使用 virtual 关键字。
最佳答案
在Cache<T>::loadObject()
, 你有这条线
obj = new T();
如果T
,该行不起作用, Mesh
在您的情况下,没有默认构造函数。
当 Cache<T>::loadObject()
是virtual
,函数的基类实现和派生类实现都被实例化。
当 Cache<T>::loadObject()
不是 virtual
,只有函数的派生类实现被实例化。函数的基类实现只有在显式使用时才会被实例化。
关于c++ - 类模板中的虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31908580/