c++ - 将指向函数的指针作为参数传递给函数

标签 c++ parameter-passing function-pointers extern-c

只是想知道是否有人可以就我在这里出错的地方给我一些建议。如果我按原样运行,我的程序工作正常,但是一旦我将注释行与其下面的行交换,我就会出错。我的目标是能够使用注释行,因为我想创建一个程序,让我将指向一个函数的指针作为另一个函数的参数传递,但到目前为止我还没有运气。

#include <iostream>
using namespace std;

double arith_op(double left, double right, double (*f)(double, double));
double addition(double left, double right);
double subtraction(double left, double right);
double multiplication(double left, double right);

int main()
{
  double left, right;
  int choice;
  double (*f[3])(double, double) = { addition, subtraction, multiplication };
  
  cout << "Enter 1 for addition, 2 for subtraction, 3 for multiplication "
       << "(-1 to end): " << endl;
  cin >> choice;

  while (choice != -1) {

    cout << "Enter a floating-point number: " << endl;
    cin >> left;

    cout << "Enter another floating-point number: " << endl;
    cin >> right;

    // double* result = arith_op(left, right, f[choice - 1](left, right));
     double result = f[choice - 1](left, right);

    if (choice == 1) {
      cout << left << " + " << right << " = " << result;
    }
    else if (choice == 2) {
      cout << left << " - " << right << " = " << result;    
    }
    else {
      cout << left << " * " << right << " = " << result;    
    }
    cout << endl;

    cout << "Enter 1 for addition, 2 for subtraction, 3 for multiplication "
     << "(-1 to end): " << endl;
    cin >> choice;
  }
}

double arith_op(double left, double right, double (*f)(double, double))
{
  return (*f)(left, right);
}

double addition(double left, double right)
{
  return left + right;
}
double subtraction(double left, double right)
{
  return left - right;
}

double multiplication(double left, double right)
{
  return left * right;
}

我应该补充一点,我的最终目标是将函数 arith_op 和其他函数打包到一个单独的文件中,然后通过将它们的原型(prototype)包含在“extern”中来使用它们。这可能是解决问题的一种奇怪方式 - 它是针对作业的,而且它们总是很奇怪。

谢谢你:)

韦德

最佳答案

你的问题出在这里的第三个参数

arith_op(left, right, f[choice - 1](left, right));

f[i](left, right) 正在调用函数给出一个 double 值,而不是将函数指针传递给 arith_op。只需删除参数列表

arith_op(left, right, f[choice - 1]);

关于c++ - 将指向函数的指针作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55367634/

相关文章:

c++ - 命令行上的大输入行在 C++ 中被截断

c++ - for循环中的数组索引

java - 如何将 TestNG 参数传递给 Cucumber?

php - 在 PHP 中保存函数的类变量

c++ - 两种函数作为参数传递方式的区别

c++ - 如何通过派生类型比较两个指向对象的指针?

c++ - std::async 使用同一个线程,我的代码没有实现并行。

c++ - Hashmap 适用于 X 个元素?

Java方法和调用方法太多次

java - 使用java中自制的打印方法打印int或double