Problem with function pointers in C ++

I plan to use function pointers to implement various functions in the class. However, I ran into some minor issues when trying to implement one of these functions.

The code is here:

std::vector<int> * (*create_vector)()
{
    std::vector<int> * vec_p = new std::vector<int>;
    return vec_p;
}

Errors are as follows:

3: [Error] expected primary-expression before '*' token
3: [Error] 'vec_p' was not declared in this scope
3: [Error] expected '}' before ';' token 
4: [Error] expected unqualified-id before 'return' 
5: [Error] expected declaration before '}' token

Is there something I don’t understand about function pointers, or is this another problem?

+5
source share
4 answers

std::vector<int> * (*create_vector)()declares a pointer to a function. Pointer. Not a function. You cannot continue the pointer and pretend to be its function and define its body. You need to declare two separately:

std::vector<int> * create_vector()
{
    std::vector<int> * vec_p = new std::vector<int>;
    return vec_p;
}

std::vector<int> * (*pcreate_vector)() = create_vector;
+8
source

You cannot declare a function and a function pointer at the same time.

Just define your function:

std::vector<int>* create_vector()
{
    std::vector<int>* vec_p = new std::vector<int>;
    return vec_p;
}

Then it is best to do a typedef (for reading code):

typedef std::vector<int>* (*create_vector_func)();

:

create_vector_func myFunc = &create_vector;
+5

, . .

:

std::vector<int>* create_vector()
{
    std::vector<int> * vec_p = new std::vector<int>;
    return vec_p;
}

create_vector(). typedef:

typedef std::vector<int>* (*func_t)();    // C++03
typedef decltype(&create_vector) func_t; // C++11

func_t f = create_vector;
auto f = create_vector; // C++11 option also.

, , , . ++ 11 , , vector vec_p ( ), . , .

+2

This is not how you define a function pointer. First define a function with the body that you have, and then assign it to a function pointer.

+1
source

All Articles