When doing Function Pointers what is the purpose of using the address-of operator vs not using it?

后端 未结 4 1509
别那么骄傲
别那么骄傲 2021-01-12 06:17

For the following code snippets why would I use one assignment vs another? thx

void  addOne(int &x)
{
    x +=1;
}

void (*inc)(int &x) = addOne;           


        
4条回答
  •  心在旅途
    2021-01-12 06:39

    From the book C++ Programming Languauge, it is cleary indicated that & and * operators are optional for pointers to functions:

    There are only two things one can do to a function: call it and take its address. The pointer obtained by taking the address of a function can then be used to call the function. For example:

    void error (string s) { /* ... */ }
    void (*efct )(string ); // pointer to function
    void f ()
    {
      efct = &error ; // efct points to error
      efct ("error "); // call error through efct
    }
    

    The compiler will discover that efct is a pointer and call the function pointed to. That is, dereferencing of a pointer to function using * is optional. Similarly, using & to get the address of a function is optional:

    void (*f1 )(string ) = &error ; // ok
    void (*f2 )(string ) = error ; // also ok; same meaning as &error
    void g ()
    {
      f1 ("Vasa"); // ok
      (*f1 )("Mary Rose"); // also ok
    }
    

    As others pointed out, pointer to member function is new/different in C++. The & is not optional to point a member and it is explained as (in C++ Programming Languauge Book):

    A pointer to member can be obtained by applying the address-of operator & to a fully qualified class member name, for example, &Std_interface::suspend.

提交回复
热议问题