Форум » C/C++ для начинающих (C/C++ for beginners) » function pointer » Ответить

function pointer

ramees: how can i use function pointer can u show me a simple example

Ответов - 1

Сыроежка: There are various contexts where you can use function pointers. For example try the following program [pre2] #include <iostream> namespace N { void ( * for_each( int *first, int *last, void f( int & x ) ) )( int & ) { for ( ; first != last; ++first ) f( *first ); return f; } } void f1( int &x ) { std::cout << x << ' '; } void f2( int &x ) { if ( x % 2 ) x = -x; } int main() { int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; N::for_each( a, a + sizeof( a ) / sizeof( *a ), f1 ); std::cout << std::endl; N::for_each( a, a + sizeof( a ) / sizeof( *a ), f2 ); N::for_each( a, a + sizeof( a ) / sizeof( *a ), f1 ); std::cout << std::endl; return 0; } [/pre2] The output will be [pre2] 0 1 2 3 4 5 6 7 8 9 0 -1 2 -3 4 -5 6 -7 8 -9 [/pre2] You could introduce a typedef name for the function pointer. In this case the code would look simpler. For example [pre2] namespace N { typedef void ( *fp )( int & ); fp for_each( int *first, int *last, fp f ) { for ( ; first != last; ++first ) f( *first ); return f; } } [/pre2] You can use for example arrays of function pointers. You can use also std::function instead of or with function pointers and so on.



полная версия страницы