gpt4 book ai didi

c++ - 函数指针类型是什么意思?

转载 作者:行者123 更新时间:2023-11-30 00:37:36 25 4
gpt4 key购买 nike

我的类作业是这样写的:

Write a declaration for a function that takes two int parameters and returns an int, and declare a vector whose elements have this function pointer type.

既然函数和 vector 都是 int,这是否正确?我对指针仍然很模糊。这是我的:

#include <iostream>
#include <vector>
using std::cin; using std::cout; using std::endl; using std::vector;

// This is my function that take two ints and returns and int
int AddFunc ( int a, int b) { int addResult; addResult = a + b; return (addResult);}

int main()
{
vector <int> v1; // Declare a vector whose elements have this functions pointer types
int add1, add2, add3 = 0;
cout << "Enter two numbers to be added with my AddFunc function: ";
cin >> add1 >> add2;
add3 = AddFunc (add1, add2);
cout << "The numbers added equal: " << add3 << endl;
v1.push_back(add3);
cout << "The first element in the vector v1 is: " << v1 [0] << endl;
return 0;
}

最佳答案

函数指针类型为int (*)(int, int)。你想要这个:

typedef int (*fptr)(int, int);

std::vector<fptr> v;

例子:

int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }

v.push_back(&add);
v.push_back(&mul);

然后是这样的:

for (f : v) { std::cout << "f(5, 7) = " << f(5, 7) << std::endl; }

关于c++ - 函数指针类型是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13002447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com