在类构造函数中传递对外部函数的引用
Pass reference to external function in class constructor
关于如何将外部函数作为参数传递给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);
}
};
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 在类构造函数中传递对外部函数的引用
- 对外部函数的调用是否强制从内存加载
- 对外部模板 constexpr 构造函数的未定义引用
- 编写一个 C++ 函数以对外部声明的数组进行操作