1. function pointer
The general function pointer can be defined as follows:
int(*func)(int,int);
Indicates a pointer to any function containing two int parameters and the returned value is in the form of Int. If such a function exists:
int add2(int x,int y){ return x+y;}
You can achieve this in actual use of the pointer FUNC:
Func = & Add2; // pointer assignment, or func = Add2; Add2 and & Add2 have the same meaning as printf ("func (3,4) = % d \ n ", func (3, 4 ));
In fact, for the sake of code porting, typedef is generally used to define the function pointer type.
typedef int(*FUN)(int,int);FUN func=&add2; func();
2. the struct contains function pointers. In fact, they can also include function pointer variables like common variables. Below is a simple implementation.
# Include "stdio. H "struct demo {int X, Y; int (* func) (INT, INT); // function pointer}; int Add2 (int x, int y) {return X + Y;} void main () {struct demo; demo. func = & Add2; // struct function pointer value printf ("func (3,4) = % d \ n", demo. func (3, 4 ));}
The above file is saved as mytest. C and compiled in vc6.0 and gcc4.
3. Functions in struct
Since C ++ mentioned when introducing classes, classes replace struct. It can be seen that the structure function is not as simple as we usually use. Not many people know that the struct can also have its own function members.
For example:
# Include "stdio. H "struct demo {int m; demo (int K) // constructor {This-> M = K; printf (" after init, M = % d \ n ", m);} void func () // General function {printf ("function of struct. \ n ") ;}}; void main () {struct demo (33); demo. func ();}
An error occurs when the file is saved as mytest1.c, vc6.0, or GCC. This may indicate that standard C does not support struct including function member forms (because the suffix. c makes VC or GCC select C compiler ). But if you change the file suffix to. cpp (that is, select C ++ to compile), there will be no errors. The result is as follows:
after init,m=33function of struct.
That is to say, in C ++, struct is allowed to contain function members, which is not supported by standard C. It is further found that C ++ even allows the struct to contain constructors, overloading, and public/private. In this way, the struct is getting closer and closer to the class!
C ++ extends the structure function. However, in C ++, to introduce object-oriented classes, the structure is just as brilliant. When we write some small programs and think there is no need to construct classes, it is much easier to select struct.
Recommended blog
Http://blog.csdn.net/bit_x/article/details/5658137