gpt4 book ai didi

C++仿函数编译错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:55:27 25 4
gpt4 key购买 nike

我有以下主程序,编译时出现此错误: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 中删除了双下划线。带有双下划线的名称保留供实现使用。

关于C++仿函数编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16327419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com