在c++中将函数作为参数传递给方法

Passing a function as a parameter to a method in C++

本文关键字:参数传递 方法 函数 c++      更新时间:2023-10-16

我想为(数学)矩阵类制作一个方法,用参数中给定的函数处理对象,但我被函数指针卡住了!

我的代码:

#include <iostream>
class Matrix{
  public:
    Matrix(int,int);
    ~Matrix();
    int getHeight();
    int getWidth();
    float getItem(int,int);
    void setItem(float,int,int);
    float getDeterminans(Matrix *);
    void applyProcessOnAll(float (*)());
  private:
    int rows;
    int cols;
    float **MatrixData;
};
Matrix::Matrix(int width, int height){
  rows = width;
  cols = height;
  MatrixData = new float*[rows];
  for (int i = 0;i <= rows-1; i++){
    MatrixData[i] = new float[cols];
  }
}
Matrix::~Matrix(){}
int Matrix::getWidth(){
  return rows;
}
int Matrix::getHeight(){
  return cols;
}
float Matrix::getItem(int sor, int oszlop){
  return MatrixData[sor-1][oszlop-1];
}
void Matrix::setItem(float ertek, int sor, int oszlop){
  MatrixData[sor-1][oszlop-1] = ertek;
}
void Matrix::applyProcessOnAll(float (*g)()){
  MatrixData[9][9]=g(); //test
}
float addOne(float num){ //test
  return num+1;
}
int main(void){
  using namespace std;
  cout << "starting...rn";
  Matrix A = Matrix(10,10);
  A.setItem(3.141,10,10);
  A.applyProcessOnAll(addOne(3));
  cout << A.getItem(10,10);
  cout << "rn";
  return 0;
}

编译器给了我这个错误:错误:没有匹配的函数调用' Matrix::applyProcessOnAll(float) '注:候选人为:注意:void Matrix::applyProcessOnAll(float ()())注意:参数1从' float '到' float ()() '

没有已知的转换

谢谢你的帮助!

现在它工作了!谢谢!

<标题> 修改部分
void Matrix::applyProcessOnAll(float (*proc)(float)){
    for(int i = 0; i <= rows-1;i++)
        for(int j = 0; j <= cols-1;j++)
            MatrixData[i][j]=proc(MatrixData[i][j]);
}

A.applyProcessOnAll(*addOne);

因为您的float (*g)()不接受参数而您的addOne接受float参数。将函数指针更改为float (*g)(float),现在它应该工作了。

你应该把函数赋值给指针,而不是调用它。

A.applyProcessOnAll(&addOne, 3); //add args argument to `applyProcessOnAll` so you can call `g(arg)` inside.

你有两个问题

第一个是Tony The Lion指出的:你指定函数不应该接受任何参数,但是你使用了一个只接受一个参数的函数。

第二个是你用函数调用的结果来调用applyProcessOnAll,而不是指向函数的指针。