简体   繁体   中英

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

I want to make a method for a (mathematical) matrix class to process objects with the function given in parameter, but I'm stuck with function pointers!

My code:

#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...\r\n";
  Matrix A = Matrix(10,10);
  A.setItem(3.141,10,10);
  A.applyProcessOnAll(addOne(3));
  cout << A.getItem(10,10);
  cout << "\r\n";
  return 0;
}

The compiler gives me this error: error: no matching function for call to 'Matrix::applyProcessOnAll(float)' note: candidate is: note: void Matrix::applyProcessOnAll(float ( )()) note: no known conversion for argument 1 from 'float' to 'float ( )()'

Thanks for the help!

Now it works! Thanks!

MODIFIED PARTS

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]);
}

and in main:

A.applyProcessOnAll(*addOne);

Because your float (*g)() does not take an argument and your addOne takes a float argument. Change your function pointer to float (*g)(float) and now it should work.

Also you should assign the function to the pointer, and not call it.

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

You have two problems.

The first is the one pointed out by Tony The Lion : you specified that the function shouldn't take any parameters but you're using a function that takes a single parameter.

The second is that you're calling applyProcessOnAll with the results of a function call, not a pointer to the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM