离开 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模板网!