在类构造函数中传递对外部函数的引用

Pass reference to external function in class constructor

本文关键字:对外部 函数 引用 构造函数      更新时间:2023-10-16

关于如何将外部函数作为参数传递给C++中的函数,还有其他问题,但我很难将这些答案应用于目标函数是新类的构造函数的情况。

以下是我要做的:

#include <iostream>
double external_function(double x, double y) {
return x * y;
}
class foo {
public:
// Initialize a function (?) as a method of class foo
double func(double, double);
// Construct an instance of the class by supplying a pointer to an external function
foo(double(*func_in)(double, double)) {
func = *func_in;
}
// When calling this method, evaluate the external function
double eval(double x, double y) {
return func(x, y);
}
};
int main() {
foo foo_instance(&external_function);
std::cout << foo_instance.eval(1.5, 2); // Should print 3
return 0;
}

我希望func作为foo类的方法,因为我稍后将编写foo的方法,用func做其他事情,例如搜索局部最小值。

类似地,这里是传递外部常量而不是函数的工作代码:

#include <iostream>
double external_value = 1.234;
class bar {
public:
// Initialize a value as a method of class bar
double val;
// Construct an instance of the class by supplying a pointer to an external value
bar(double* val_in) {
val = *val_in;
}
// When calling this method, return the external function
double eval() {
return val;
}
};
int main() {
bar bar_instance(&external_value);
std::cout << bar_instance.eval(); // 1.234
return 0;
}

像这个

class foo {
public:
// Initialize a function pointer as a method of class foo
double (*func)(double, double);
// Construct an instance of the class by supplying a pointer to an external function
foo(double(*func_in)(double, double)) {
func = func_in;
}
// When calling this method, evaluate the external function
double eval(double x, double y) {
return func(x, y);
}
};

在您的版本中,func是一个未定义的类方法,而不是您希望它成为的函数指针

以下是使用std::function:的示例

#include <functional>
class foo {
public:
// Initialize a function as a method of class foo
std::function<double(double, double)> func;
// Construct an instance of the class by supplying a pointer to an external function
foo(std::function<double(double, double)> func_in) {
func = func_in;
}
// When calling this method, evaluate the external function
double eval(double x, double y) {
return func(x, y);
}
};