gpt4 book ai didi

C++ 使用模板成员函数继承类

转载 作者:太空宇宙 更新时间:2023-11-04 16:20:28 24 4
gpt4 key购买 nike

我在编写资源类时遇到问题:

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:未解析的外部符号“"public: char * const & __thiscall BaseResource::GetValue(void)const "(??$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*>();

在我看来,这应该创建一个 Resource 实例,它包含一个 char* 并可以返回它。

谁能告诉我我在哪里做错导致了这个?

最佳答案

未实现以下方法:

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

我希望您不打算将它们虚拟化,因为那行不通。模板方法不能成为虚拟的。由于它们没有实现,这无疑解释了链接问题。

关于C++ 使用模板成员函数继承类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17349991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com