C++笔记之从数组指针到函数数组指针(使用using name和std::function)
参考笔记:
C++之指针探究(三):指针数组和数组指针
C++之指针探究(十三):函数指针数组
C++之指针探究(二):一级指针和一维数组
C++之指针探究(十一):函数名的本质和函数指针
C++笔记之从使用函数指针和typedef到使用std::function和using
C++之指针探究(八):指针函数和函数指针
code review!
文章目录
- C++笔记之从数组指针到函数数组指针(使用using name和std::function)
- 1.指向数组的指针
- 2.指向动态数组的指针
- 3.函数指针数组和std::function、using结合使用的例程
- 形式一:MathFunction mathFunctions[] = {add, subtract, multiply, divide};
- 形式二:MathFunction *mathFunctions[] = {add, subtract, multiply, divide};
- 形式三:MathFunction *mathFunctions = new MathFunction[4];
- 附代码
1.指向数组的指针
2.指向动态数组的指针
3.函数指针数组和std::function、using结合使用的例程
形式一:MathFunction mathFunctions[] = {add, subtract, multiply, divide};
形式二:MathFunction *mathFunctions[] = {add, subtract, multiply, divide};
形式三:MathFunction *mathFunctions = new MathFunction[4];
附代码
形式一:
#include <iostream>
#include <functional>// 定义不同类型的函数
int add(int a, int b) {return a + b;
}int subtract(int a, int b) {return a - b;
}double multiply(double a, double b) {return a * b;
}double divide(double a, double b) {return a / b;
}// 创建函数指针数组类型
using MathFunction = std::function<double(double, double)>;int main() {// 创建函数指针数组MathFunction mathFunctions[] = {add, subtract, multiply, divide};// 使用函数指针数组调用不同函数double x = 10.0, y = 5.0;for (const MathFunction &func : mathFunctions) {std::cout << func(x, y) << std::endl;}return 0;
}
形式二:
#include <iostream>
#include <functional>// 定义不同类型的函数
int add(int a, int b) {return a + b;
}int subtract(int a, int b) {return a - b;
}double multiply(double a, double b) {return a * b;
}double divide(double a, double b) {return a / b;
}// 创建函数指针数组类型
using MathFunction = std::function<double(double, double)>;int main() {// 创建指针数组并初始化MathFunction *mathFunctions[] = {add, subtract, multiply, divide};// 使用指针数组调用不同函数double x = 10.0, y = 5.0;for (MathFunction *func : mathFunctions) {std::cout << (*func)(x, y) << std::endl;}return 0;
}
形式三:
#include <iostream>
#include <functional>// 定义不同类型的函数
int add(int a, int b) {return a + b;
}int subtract(int a, int b) {return a - b;
}double multiply(double a, double b) {return a * b;
}double divide(double a, double b) {return a / b;
}// 创建函数指针数组类型
using MathFunction = std::function<double(double, double)>;int main() {// 创建指针数组并初始化MathFunction *mathFunctions = new MathFunction[4];mathFunctions[0] = add;mathFunctions[1] = subtract;mathFunctions[2] = multiply;mathFunctions[3] = divide;// 使用指针数组调用不同函数double x = 10.0, y = 5.0;for (int i = 0; i < 4; ++i) {std::cout << mathFunctions[i](x, y) << std::endl;}// 释放内存delete[] mathFunctions;return 0;
}