如何使用指向函数的指针数组以及C++11中auto的用法?


//fun_ptr_deep -- an aray of function pointers 
#include <iostream>

//various notations, same signatures
const double * f1( const double arr[], int n);
const double * f2( const double [], int n);
const double * f3( const double *, int n);

int main()
{
	using namespace std;
	double av[3] = { 1.0, 2.0, 3.0 };

	const double *(*p1) (const double *, int) = f1;//pointer to a function
	auto p2 = f2;  //c++ 11 automatic type deduction
	//pre--c++ 11 can use the following code insdead
	const double *(*p3) (const double *, int) = f3;

	cout << "Using pointers to functions:\n";
	cout << "Address value:\n";
	cout << (*p1)(av, 3) << ": " << *(*p1)( av, 3) << endl;
	cout << p2(av, 3) << ": " << *p2( av, 3) << endl;
	cout << p3(av, 3) << ": " << *p3( av, 3) << endl;


	// pa an array of pointers
	//auto doesn't work with list initialization
	const double *(*pa[3])(const double *, int ) = {f1, f2, f3}; // 声明了一个指向函数的指针数组
	// but it does work for initializing to a single value
	//pb a pointer to first element of pa
	auto pb = pa;
	cout << "\nUsing an array of pointers to functions:\n";
	cout << "Address Value\n";
	for (int i = 0; i < 3; i++)
		cout <<  pa[i](av, 3) << ": " << *pa[i](av, 3) << endl;

	cin.get();
	return 0;
}

const double * f1(const double *arr, int n)
{
	return arr;
}

const double * f2(const double arr[], int n)
{
	return arr + 1;
}

const double * f3(const double arr[], int n)
{
	return arr + 2;
}

运行效果:

如何使用指向函数的指针数组以及C++11中auto的用法?_第1张图片



你可能感兴趣的:(auto,函数指针,C++11)