C++ 中函数指针的 Typedef
本文将解释 C/C++ 中 typedef 的用途。 我们将进一步讨论如何将 typedef 与函数指针一起使用以及使用它的好处是什么。
我们首先讨论 typedef 及其常见用途。
typedef 关键字
typedef 代表类型定义。 顾名思义,typedef 是一种为现有数据类型(变量类型)分配新名称的方法。
例如,如果要存储整型变量,则数据类型将为 int。 类似地,字符或字符串数据类型用于单词或短语。
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a =10;
string greeting="Hello!";
return 0;
}
在 typedef
的帮助下,您可以将自己从实际使用的类型中分离出来,而更多地关注变量应该表示什么含义。 这使得编写干净的代码变得更简单,但也使编辑代码变得更简单。
例如,如果您要在板球比赛后记录三名不同球员的发言,则可以使用 typedef。
#include <iostream>
using namespace std;
int main()
{
typedef char* statement;
statement PlayerA="I played bad";
statement PlayerB="I played very well";
statement PlayerC=" I could not get the chance to Bat";
cout<<"Player A said:"<<PlayerA;
return 0;
}
在上面的代码中,char*
是一个字符指针,我们在其上应用了 typedef 关键字,以便使用新的 name 语句更改此数据类型。 在这种情况下,这个新别名更有意义,因为我们正在记录玩家的陈述。
因此,typedef 增强了代码的可读性。
typedef 也可以与函数指针一起使用。 在开始之前,让我们简单介绍一下函数指针。
函数指针
在 C++ 中,指针是保存变量的内存地址的变量。 类似地,函数指针是保存函数地址的指针。
可以使用以下代码声明函数指针:
int (*point_func)(int,int);
在上面的代码中,point_func是一个指针,它指向一个函数,该函数有两个整数变量作为参数,int作为返回类型。
带函数指针的 typedef
对于带有函数指针的 typedef 来说,语法看起来有些奇怪。 您只需将 typedef 关键字放在函数指针声明的开头即可。
typedef int (*point_func)(int,int);
上面的命令意味着您定义了一个名为 point_func 的新类型(一个带有两个 int 参数并返回一个整数的函数指针,即 int(*) (int, int)
)。 现在您可以使用这个新名称来声明指针。
我们来看下面的编程示例:
#include <iostream>
using namespace std;
int abc(int x1, int x2){
return (x1 * x2);
}
int main()
{
typedef int (*pair_func)(int,int);
pair_func PairProduct; // PairProduct is pointer of type pair_func
PairProduct=&abc; // PairProduct pointer holds the address of function abc
int product= (*PairProduct) (20, 5);
cout<<"The product of the pair is: "<<product;
return 0;
}
输出:
The product of the pair is: 100
到目前为止,如果在函数指针之前使用 typedef 的话,它的作用已经很清楚了。 在上面的代码中,abc 函数接受两个参数并返回它们的乘积。
在主函数中,我们使用 typedef 为函数指针定义一个新名称(即pair_func)。 然后,我们定义了pair_func类型的PairProduct并分配了函数abc地址。
之后,我们通过取消引用指针 PairProduct(更简单的语法)并传递两个参数来调用函数 abc。
相关文章
Arduino 复位
发布时间:2024/03/13 浏览次数:315 分类:C++
-
可以通过使用复位按钮,Softwarereset 库和 Adafruit SleepyDog 库来复位 Arduino。
Arduino 的字符转换为整型
发布时间:2024/03/13 浏览次数:181 分类:C++
-
可以使用简单的方法 toInt()函数和 Serial.parseInt()函数将 char 转换为 int。
Arduino 串口打印多个变量
发布时间:2024/03/13 浏览次数:381 分类:C++
-
可以使用 Serial.print()和 Serial.println()函数在串口监视器上显示变量值。