我有以下主程序,编译时出现此错误:double squarer(double, SineFunctor&) 的 undefined symbol 为什么链接器找不到函数平方器?
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.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;
}
模板定义必须在头文件中给出,因为编译器需要确切地知道它应该实例化什么。将 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
中删除了双下划线。带有双下划线的名称保留供实现使用。
我是一名优秀的程序员,十分优秀!