Ism*_*ush 9 c++ function-pointers
下面使用一个简单的函数指针,但如果我想存储该函数指针怎么办?在这种情况下,变量声明会是什么样的?
#include <iostream>
#include <vector>
using namespace std;
double operation(double (*functocall)(double), double wsum);
double get_unipolar(double);
double get_bipolar(double);
int main()
{
double k = operation(get_bipolar, 2); // how to store get_bipolar?
cout << k;
return 0;
}
double operation(double (*functocall)(double), double wsum)
{
double g = (*functocall)(wsum);
return g;
}
double get_unipolar(double wsum)
{
double threshold = 3;
if (wsum > threshold)
return threshold;
else
return threshold;
}
double get_bipolar(double wsum)
{
double threshold = 4;
if (wsum > threshold)
return threshold;
else
return threshold;
}
Run Code Online (Sandbox Code Playgroud)
您的代码几乎已经完成,您似乎只是称之为不正确,它应该是简单的
double operation(double (*functocall)(double), double wsum)
{
double g;
g = functocall(wsum);
return g;
}
Run Code Online (Sandbox Code Playgroud)
如果你想要一个变量,它的声明方式是相同的
double (*functocall2)(double) = get_bipolar;
Run Code Online (Sandbox Code Playgroud)
或者已经宣布
functocall2 = get_bipolar;
Run Code Online (Sandbox Code Playgroud)
给你一个名为functocall2get_bipolar 的变量,通过简单的方式调用它
functocall2(mydouble);
Run Code Online (Sandbox Code Playgroud)
或者将其传递给
operation(functocall2, wsum);
Run Code Online (Sandbox Code Playgroud)
你已经(几乎)在你的代码中拥有它:
double (*functocall)(double) = &get_bipolar;
Run Code Online (Sandbox Code Playgroud)
这定义了一个名为函数指针functocall指向get_bipolar.