1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <iostream>
int plus( int a, int b ) { return a+b ; }
int minus( int a, int b ) { return a-b ; }
int multiplies( int a, int b ) { return a*b ; }
int i = 10, j = 20, k = 30 ;
int main()
{
using function_type = int(int,int) ;
using pointer_to_function = function_type* ;
using pointer_to_int = int* ;
pointer_to_function pfn = nullptr ;
// pfn can point to any function of type int(int,int) (or it can be null)
pointer_to_int pint = nullptr ;
// pint can point to any object of type int (or it can be null)
// pointers are converted to bool; nullptr => false
std::cout << std::boolalpha << pfn << ' ' << bool(pint) << '\n' ; // false false
pfn = &plus ; // pfn now points to 'plus'
pint = &i ; // pint now points to 'i'
// pointers are converted to bool; non-null pointer => true
std::cout << pfn << ' ' << bool(pint) << '\n' ; // true true
// call the function / access the int via pointer
std::cout << (*pfn)(4,2) << ' ' << *pint << '\n' ; // 6 10 ; plus(4,2) == 6, i == 10
pfn = plus ; // pfn now points to 'plus' ; &plus is implied
std::cout << pfn(4,2) << '\n' ; // 6 ( pfn(4,2) => (*pfn)(4,2) ; plus(4,2) == 6
pfn = minus ; // pfn now points to 'minus'
pint = &j ; // pint now points to 'j'
std::cout << pfn << ' ' << bool(pint) << '\n' ; // true true
std::cout << pfn(4,2) << ' ' << *pint << '\n' ; // 2 20 ; minus(4,2) == 2, j == 20
pfn = multiplies ; // pfn now points to 'multiplies'
pint = &k ; // pint now points to 'k'
std::cout << pfn << ' ' << bool(pint) << '\n' ; // true true
std::cout << pfn(4,2) << ' ' << *pint << '\n' ; // 8 30 ; multiplies(4,2) == 8, k == 30
}
|