只是想知道是否有人可以就我在这里出错的地方给我一些建议。如果我按原样运行我的程序可以正常工作,但是一旦我将注释行与它下面的行交换,我就会得到错误。我的目标是能够使用注释行,因为我想创建一个程序,让我将指向函数的指针作为参数传递给另一个函数,但到目前为止我没有运气。
#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 和其他函数打包在一个单独的文件中,然后通过将它们的原型包含在“extern”中来使用它们。这可能是解决问题的一种奇怪的方法——它是为了分配,而且它们总是很奇怪。
谢谢 :)
韦德