我有以下主程序,在编译时会出现此错误: 双平方的未定义符号(double,SineFunctor&) 为什么链接器不能找到函数squarer?
include <iostream>
#include "SineFunctor.h"
#include "squarer.h"
int main()
{
const double PI = 3.141592L;
double x = 1.0;
double y;
// initialize function parameters
SineFunctor sine(2., 10.*PI, 0.);
// pass functions sine to function squarer
y = squarer(x, sine);
return 0;
}
以下是SineFunctor的文件
// SineFunctor.h
#ifndef __functor_example__SineFunctor__
#define __functor_example__SineFunctor__
#include <iostream>
class SineFunctor {
public:
// constructor to set function parameters
SineFunctor(const double amp, const double freq, const double phase);
// function evaluation using overloaded operator()
double operator() (const double t);
private:
double _amp;
double _freq;
double _phase;
};
#endif /* defined(__functor_example__SineFunctor__) */
// SineFunctor.cpp
#include <cmath>
#include "SineFunctor.h"
// constructor to set function parameters
SineFunctor::SineFunctor(const double amp, const double freq, const double phase) {
_amp = amp;
_freq = freq;
_phase = phase;
}
// function evaluation using overloaded operator()
double SineFunctor::operator() (const double t) {
return _amp * sin(_freq * t + _phase);
}
和squarer&gt;
// squarer.h
#ifndef __functor_example__squarer__
#define __functor_example__squarer__
#include <iostream>
template <class F>
double squarer(const double x, F& func);
#endif /* defined(__functor_example__squarer__) */
// squarer.cpp
#include "squarer.h"
template <class F>
double squarer(const double x, F& func) {
double y = func(x);
return y * y;
}
答案 0 :(得分:1)
模板定义必须在头文件中给出,因为编译器需要准确知道它应该实例化的内容。将squarer
的定义移到头文件中:
// squarer.h
#ifndef functor_example__squarer
#define functor_example__squarer
template <class F>
double squarer(const double x, F& func) {
double y = func(x);
return y * y;
}
#endif
请注意,我已从#define
删除了双下划线。具有双下划线的名称保留供实现使用。
答案 1 :(得分:0)
模板函数要么需要在标题中,要么实例化为cpp中的所有类型。