2013-06-27 53 views
0

有问题I'm而编写资源类:与模板成员函数的C++继承类

class BaseResource { 
protected: 
    unsigned int size; 

public: 
    virtual ~BaseResource() {} 
    template<class T> const T& GetValue() const; 
    template<class T, class U> void GetValue(const U& rhs); 

    unsigned int GetSize() { 
     return this->size; 
    } 
    void SetSize(unsigned int size) { 
     this->size = size; 
    } 
}; 

template<class T> 
class Resource : public BaseResource { 
    T value; 

public: 
    virtual ~Resource() {}  
    Resource(unsigned int size, const T& rhs) { this->size = size; this->value = rhs; } 

    const T& GetValue() const {return value;} 
    void SetValue(const T& rhs) {value=rhs;} 
}; 

我觉得上面的类正确定义,所以我 不明白为什么下面的代码生成一个链接错误:

Test.obj:错误LNK2001:无法解析的外部符号 “” 市民:char * const的& __thiscall BaseResource ::的GetValue(无效)常量 “(?? $ @的GetValue PAD @ BaseResource @@ QBEABQADXZ)”。

char* c = new char[3]; 
c[0] = '1'; 
c[1] = '2'; 
c[2] = '3'; 
BaseResource* resource = new Resource<char*>(3, c); 
char* loadedResource = resource->GetValue<char*>(); 

在我看来,这应该创建一个资源的实例持有一个char *并可以返回它。

有人可以告诉我,我在哪里做了这个错误吗?

回答

2

这些函数的实现应该与类相同的头文件中。在这种情况下,您已经实例化了模板函数,并且具体的实例化函数没有被定义。每次使用模板时,都需要在使用该功能的翻译单元中包含该功能的定义。

编辑


这是基本的理念。您需要定义植入,以便在类实例化时类已完全定义。

public: 
    virtual ~BaseResource() {} 
    template<class T> const T& GetValue() const 
    { 
     return someT; 
    } 
    template<class T, class U> void GetValue(const U& rhs) 
    { 
     return someT; 
    } 

    unsigned int GetSize() { 
     return this->size; 
    } 
    void SetSize(unsigned int size) { 
     this->size = size; 
    } 
}; 
+0

嗯好吧,这似乎合乎逻辑。 那么你能明确告诉我如何解决所示情况的问题吗? – Xenogenesis

2

下面的方法未实现:

template<class T> const T& GetValue() const; 
template<class T, class U> void GetValue(const U& rhs); 

我希望你是不是在让他们的虚拟因为西港岛线不工作规划。 模板方法不能做成虚拟的。 因为它们没有被实现,所以明确解释了链接问题。