Using C ++ Function Pointer

I am new to C ++, studying a function pointer recently, a little confused about using a function pointer;

I practiced the following code:

#include <iostream>
#include <sstream>
using namespace std;

int subtraction(int a,int b){
    return a-b;
}

int main(int argc, const char * argv[])
{

    int (*minus)(int,int)=subtraction;
    cout<<minus(5,4);

    return 0;
}

it works well; therefore, I will try to change a little:

#include <iostream>
#include <sstream>
using namespace std;

int subtraction(int a,int b){
    return a-b;
}

int main(int argc, const char * argv[])
{

    int *minus(int,int)=subtraction;//only here different!
    cout<<minus(5,4);

    return 0;
}

I practiced it in Xcode on Mac, it gave me an error:

Illegal initializer (only variables can be initialized)

but I think the compiler can recognize that the two are the same, why should it have a pair of parentheses?

+4
source share
3 answers

In source code

int (*minus)(int,int)=subtraction;

declares minusas a function pointerwhich takes a parameter int, intand returns int.

In your second code

int *minus(int,int)=subtraction;

minus , int, int int *.

( ) , .

+9

. () , *. , .

int *minus(int, int)

: , (int * ).

int (*minus)(int, int)

: "", , .

+3

C++ iostream, , ++.

In such a scenario, it is best to use a class template std::functioninstead of a function pointer syntax that is error prone.

#include <iostream>
#include <sstream>
#include <functional>


int subtraction(int a,int b){
    return a-b;
}

int main(int argc, const char * argv[])
{
    std::function<int(int,int)> minus = subtraction;
    //int (*minus)(int,int)=subtraction;
    std::cout<<minus(5,4);

    return 0;
}

Alternatively, if you still want to continue the function pointer, it is recommended to use typedefs

#include <iostream>
int subtraction(int a,int b){
    return a-b;
}
typedef int (*MINUS)(int,int);
int main(int argc, const char * argv[])
{
    MINUS minus = subtraction;
    //int (*minus)(int,int)=subtraction;
    std::cout<<minus(5,4);

    return 0;
}

And finally, another widely used option is the use of functors.

#include <iostream>
struct MINUS
{
    int operator()(int a,int b){
        return a-b;
    }
};
int main(int argc, const char * argv[])
{
    //int (*minus)(int,int)=subtraction;
    MINUS minus;
    std::cout<<minus(5,4);

    return 0;
}
+2
source

All Articles