繁体   English   中英

将函数作为参数传递给C ++中的方法

[英]Passing a function as a parameter to a method in C++

我想为一个(数学)矩阵类创建一个方法,用参数中给出的函数处理对象,但是我坚持使用函数指针!

我的代码:

#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;
}

编译器给我这个错误:错误:没有匹配函数调用'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.

你有两个问题。

第一个是托尼狮子指出的那个 :你指定该函数不应该采用任何参数,但你使用的函数只需要一个参数。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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