专业编程基础技术教程

网站首页 > 基础教程 正文

C++|函数与指针:简单了解函数指针和指针函数

ccvgpt 2024-08-05 12:24:32 基础教程 10 ℃

函数指针是指指向一个函数的指针(pointer to function),如:

int (*pf)(int);

上面的代码要按运算符的优先级去理解,()的优先级最高,所以上面*pf加上前面的int表示是一个int指针的声明,后面跟的(int)表示是函数,则int (*pf)(int)是指一个int类型的函数指针,

C++|函数与指针:简单了解函数指针和指针函数

指针函数是指一个返回指针的函数,如:

int *pf(int);

1 函数指针

程序运行时,代码和数据都是分类存储在内存的不同区块中,所以函数也如同数据一样,有其内存地址,其内存地址可以被赋值给一个指针,这样的指针就叫函数指针。

#include <iostream>
using namespace std;
int f1(int);
int (*pf)(int);
int main()
{
	pf = f1;
	int x = f1(4);
	int y = (*pf)(4);
	cout<<x<<" "<<y;
	cin.get();
	return 0;
}
int f1(int n)
{
	return n*n;
}

int y = (*pf)(4);也可以写成:

int y = pf(4);

函数指针最经典的应用就是用作函数参数进行调用,这样一个使用函数指针做参数的函数就能灵活调用不同的函数。

2 指针函数

指针函数首先是一个函数,是一个返回指针的函数,如以下的指针函数的声明:

int * f1(int ar[], int n);

以下两个写法效果相同:

int * f1(int [], int n);

int * f1(int *, int n);

如何写一个指向指针函数的函数指针呢?

int *(*pf)(int *, int n) = f1;

以下是一个指针函数的使用实例:

附代码1:

#include <iostream>
double betsy(int);
double pam(int);
// second argument is pointer to a type double function that
// takes a type int argument
void estimate(int lines, double (*pf)(int));
int main()
{
 using namespace std;
 int code;
 cout << "How many lines of code do you need? ";
 cin >> code;
 cout << "Here's Betsy's estimate:\n";
 estimate(code, betsy);
 cout << "Here's Pam's estimate:\n";
 estimate(code, pam);
 cin.get();
 cin.get();
 return 0;
}
double betsy(int lns)
{
 return 0.05 * lns;
}
double pam(int lns)
{
 return 0.03 * lns + 0.0004 * lns * lns;
}
void estimate(int lines, double (*pf)(int))
{
 using namespace std;
 cout << lines << " lines will take ";
 cout << (*pf)(lines) << " hour(s)\n";
}

附代码2:

#include <iostream>
char * buildstr(char c, int n);
int main()
{
 using namespace std;
 int times;
 char ch;
 cout << "Enter a character: ";
 cin >> ch;
 cout << "Enter an integer: ";
 cin >> times;
 char *ps = buildstr(ch, times);
 cout << ps << endl;
 delete [] ps; // free memory
 ps = buildstr('+', 20); // reuse pointer
 cout << ps << "-DONE-" << ps << endl;
 delete [] ps; // free memory
 cin.get();
 cin.get();
 return 0;
}
// builds string made of n c characters
char * buildstr(char c, int n)
{
 char * pstr = new char[n + 1];
 pstr[n] = '\0'; // terminate string
 while (n-- > 0)
 pstr[n] = c; // fill rest of string
 return pstr; 
}

-End-

Tags:

最近发表
标签列表