调用函数时,是否可以在被调用函数的名称后附加数字或字符?
When calling a function, is it possible to append a number or a character to the name of the function being called?
所以我有多个函数,它们在其他方面具有相同的名称,但每个函数名称的末尾都有一个不同的数字,如下所示:
void bark0() {
cout << "A small amount of dogs are barking" << endl;
}
void bark1() {
cout << "Some dogs are barking" << endl;
}
void bark2() {
cout << "Bark Bark!" << endl;
}
是否可以从 for 循环中调用所有这些函数,以便 int i 成为当前要调用的函数?
for (int i = 0; i < 3; i++) {
// Call bark + i at the end || For example bark2(); when i == 2
}
或者是否可以调用以用户输入的数字结尾的函数?
int input;
cin >> input;
bark+input();
我知道您可以使用指向函数的指针映射,但我想知道是否有像这样调用函数的方法。
编辑:我不想使用参数,因为函数应该做完全不同的事情。这些吠声 0、1 和 2 只是示例。
你可以为你的函数使用一个参数而不是这样:
void bark(int index) {
cout << "Dog " << index << " is barking" << endl;
}
然后
int input;
cin >> input;
bark(input);
并征求您的意见:
I want these functions to do entirely different things
没问题,也可以用switch或者if来分开作品
void bark(int index) {
switch(index){
case 1:
// ....
break;
case 2:
// ....
break;
case 3:
// ....
break;
}
请阅读this doc(见页尾表格)
没有。您不能根据在运行时确定的名称调用函数。这种事情在支持反射的语言中是可能的,但c++不是这样的语言。
在您的简单示例中,您可以像 Arash Hawaii 建议的那样使用数字作为函数参数。
the functions are supposed to be doing entirely different things
在那种情况下,争论不是一个好主意。更好的选择是使用函数指针数组。使用整数输入作为数组的索引。并确保验证输入!
您不能在 C/C++ 中执行此操作,因为函数名称在编译后不是机器代码的一部分。
我会通过创建函数指针数组然后在循环中调用索引函数指针来解决这个问题。
您可以将函数作为函子或 lambda 存储在使用 int 作为键的哈希映射中,并以这种方式循环遍历它们,或者存储一个数组而不是映射。
其他回答已经说明了你说的不可能。但是没有人会阻止您手动执行类似的操作:
using func_type = std::function<void()>;
func_type functions[3] = { &bark0, &bark1, &bark2 };
for (int i = 0; i < 3; i++) functions[i]();
所以我有多个函数,它们在其他方面具有相同的名称,但每个函数名称的末尾都有一个不同的数字,如下所示:
void bark0() {
cout << "A small amount of dogs are barking" << endl;
}
void bark1() {
cout << "Some dogs are barking" << endl;
}
void bark2() {
cout << "Bark Bark!" << endl;
}
是否可以从 for 循环中调用所有这些函数,以便 int i 成为当前要调用的函数?
for (int i = 0; i < 3; i++) {
// Call bark + i at the end || For example bark2(); when i == 2
}
或者是否可以调用以用户输入的数字结尾的函数?
int input;
cin >> input;
bark+input();
我知道您可以使用指向函数的指针映射,但我想知道是否有像这样调用函数的方法。
编辑:我不想使用参数,因为函数应该做完全不同的事情。这些吠声 0、1 和 2 只是示例。
你可以为你的函数使用一个参数而不是这样:
void bark(int index) {
cout << "Dog " << index << " is barking" << endl;
}
然后
int input;
cin >> input;
bark(input);
并征求您的意见:
I want these functions to do entirely different things
没问题,也可以用switch或者if来分开作品
void bark(int index) {
switch(index){
case 1:
// ....
break;
case 2:
// ....
break;
case 3:
// ....
break;
}
请阅读this doc(见页尾表格)
没有。您不能根据在运行时确定的名称调用函数。这种事情在支持反射的语言中是可能的,但c++不是这样的语言。
在您的简单示例中,您可以像 Arash Hawaii 建议的那样使用数字作为函数参数。
the functions are supposed to be doing entirely different things
在那种情况下,争论不是一个好主意。更好的选择是使用函数指针数组。使用整数输入作为数组的索引。并确保验证输入!
您不能在 C/C++ 中执行此操作,因为函数名称在编译后不是机器代码的一部分。
我会通过创建函数指针数组然后在循环中调用索引函数指针来解决这个问题。
您可以将函数作为函子或 lambda 存储在使用 int 作为键的哈希映射中,并以这种方式循环遍历它们,或者存储一个数组而不是映射。
其他回答已经说明了你说的不可能。但是没有人会阻止您手动执行类似的操作:
using func_type = std::function<void()>;
func_type functions[3] = { &bark0, &bark1, &bark2 };
for (int i = 0; i < 3; i++) functions[i]();