【问题标题】:"Undefined symbols" linker error with simple template class简单模板类的“未定义符号”链接器错误
【发布时间】:2010-11-03 05:12:14
【问题描述】:

已经离开 C++ 几年了,我从以下代码中得到一个链接器错误:

基因.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++ 中以获得乐趣和练习。

【问题讨论】:

标签: c++ templates unsatisfiedlinkerror


【解决方案1】:

必须在实例化给定模板类之前包含模板定义(代码中的 cpp 文件),因此您必须在头文件中包含函数定义,或者在使用类之前#include cpp 文件(或在数量有限的情况下进行显式实例化)。

【讨论】:

【解决方案2】:

包含包含模板类函数实现的 cpp 文件是可行的。但是,恕我直言,这很奇怪而且很尴尬。一定有一种更巧妙的方式来做到这一点?

如果您只有几个不同的实例要创建,并且事先知道它们,那么您可以使用“显式实例化”

它的工作原理是这样的:

在gene.cpp的顶部添加以下行

template class Gene<int>;
template class Gene<float>;

【讨论】:

    【解决方案3】:

    if(value &gt;= this-&gt;minValue &amp;&amp; value &lt;= this-&gt;minValue) 中,第二个minValue 应该是maxValue,不是吗?

    回应肖恩所说的:错误信息是什么?您已经定义并声明了函数,但您没有在任何地方使用它们,我也没有看到错误(除了错字)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-08
      • 2014-06-12
      • 1970-01-01
      • 2016-07-14
      • 2012-03-10
      相关资源
      最近更新 更多