在下面的代码中:
#include "Simple_window.h"
#include "Graph.h"
int fac(int n) // factorial(n); n!
{
int r = 1;
while(n>1) {
r *= n;
--n;
}
return r;
}
double term(double x,int n) { return pow(x,n)/fac(n); }
double expe(double x,int n) // sum of n terms for x
{
double sum = 0;
for(int i = 0; i<n; ++i) sum += term(x,i);
return sum;
}
int main() {
Simple_window win {Point{100,100},xmax,ymax,""};
for(int n = 0; n<50; ++n) {
ostringstream ss;
ss << "exp approximation; n==" << n;
win.set_label(ss.str());
// get next approximation:
Function e {[n](double x) { return expe(x,n); },
-10,10,Point{300,300},200,30,30; // ***this line doesn't compile***
win.attach(e);
win.wait_for_button();
win.detach(e);
}
}
从Stroustrup的《使用C++的原理和实践》一书中,当我尝试编译本地变量n
时未使用它,并给出了错误消息:No instance of the constructor Graph_lib::Function::Function coincides with the argument list
问题是什么?
顺便说一句,用于书籍的支持代码是https://web.archive.org/web/20191217104940/http://www.stroustrup.com/Programming/PPP2code
最佳答案
您的帖子距离Minimal Reproducible Example不近
这是“最小可复制示例”的示例。
在Graph.h中,Function
带有Fct
变量。
其中Fct
是typedef double Fct(double);
。
但是,lambda不会自动转换为函数,除非它不会通过捕获任何内容来创建闭包对象。
检查此example
typedef double Fct ( double );
struct Foo{
Foo( Fct f );
};
int main(){
int n(1);
Foo f{ [](double x){ return x; } };
//Foo f{ [n](double x){ return x*n; } }; // <=== this won't compile
}
相关文章:https://stackoverflow.com/a/45565056/4123703要将
n
传递到函数f
中,您可以typedef double Fct ( double );
更改为typedef double Fct(double,int);n
编写一个函数。n
。关于c++ - 如何在此C++ lambda表达式中采用局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63351768/