問題描述
離開 C++ 幾年了,我從以下代碼中收到鏈接器錯誤:
Been away from C++ for a few years and am getting a linker error from the following code:
基因.h
#ifndef GENE_H_INCLUDED
#define GENE_H_INCLUDED
template <typename T>
class Gene {
public:
T getValue();
void setValue(T value);
void setRange(T min, T max);
private:
T value;
T minValue;
T maxValue;
};
#endif // GENE_H_INCLUDED
基因.cpp
#include "Gene.h"
template <typename T>
T Gene<T>::getValue() {
return this->value;
}
template <typename T>
void Gene<T>::setValue(T value) {
if(value >= this->minValue && value <= this->minValue) {
this->value = value;
}
}
template <typename T>
void Gene<T>::setRange(T min, T max) {
this->minValue = min;
this->maxValue = max;
}
如果對任何人都很重要,請使用 Code::Blocks 和 GCC.此外,為了好玩和練習,顯然將一些 GA 內容移植到 C++.
Using Code::Blocks and GCC if it matters to anyone. Also, clearly porting some GA stuff to C++ for fun and practice.
推薦答案
必須在實例化給定模板類之前包含模板定義(代碼中的 cpp 文件),因此您必須在標頭,或在使用類之前#include cpp 文件(或者如果數量有限,則進行顯式實例化).
The template definition (the cpp file in your code) has to be included prior to instantiating a given template class, so you either have to include function definitions in the header, or #include the cpp file prior to using the class (or do explicit instantiations if you have a limited number of them).
這篇關于“未定義符號"簡單模板類的鏈接器錯誤的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!