C++指向函数动态数组的指针
C++ Pointer to Dynamic Array of functions?
我创建了一个指向函数的指针数组,我想知道是否可以动态创建指针数组,正如您在下面看到的,我想动态更改数组长度,目前为 2。
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
void func1(int);
void func2(int);
int main()
{
void (*func[2])(int) = { &func1, &func2 };
func[0](10);
func[1](20);
cin.ignore();
return 0;
}
void func1(int n)
{
cout << "In func1()ntThe value is: " << n << endl;
}
void func2(int n)
{
cout << "In func2()ntThe value is: " << n << endl;
}
为函数类型创建一个 typedef:
typedef void (*FunctionType)(int);
然后做一个普通的动态数组:
FunctionType* func = new FunctionType[2];
然后,您可以分配:
func[0] = &func1;
并致电:
func[0](1);
动态更改数组大小的唯一方法是删除指针,然后使用适当的大小重新创建它。
//Placeholder
using Function = void(*)(int);
//We have 2 functions
Function* func = new Function[2];
//Assigning...
func[0] = &func1;
func[1] = &func2;
//Doing stuff...
//Oh no! We need a third function!
Function* newfunc = new Function[3]; //Create new array
newfunc[0] = func[0];
newfunc[1] = func[1]; //Better use a loop
newfunc[2] = &func3;
//Delete old array
delete func;
//Reassign to new array
func = newfunc;
//Now 'func' changed size :)
您将使用std::vector
避免所有这些指针内容:
//Placeholder
using Function = void(*)(int);
//Create std::vector
std::vector<Function> func{ &func1, &func2 }; //Default initialize with 'func1' and 'func2'
//Do stuff....
//Oh no! We need a third function
func.emplace_back(&func3);
//Now 'func' has 3 functions
希望下面的代码能帮助你:
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
void func1(int);
void func2(int);
int main()
{
std::vector<void(*)(int)> funcPointers;
funcPointers.push_back(&func1);
funcPointers.push_back(&func2);
funcPointers[0](10);
funcPointers[1](20);
cin.ignore();
return 0;
}
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”