【问题标题】:Passing a function as a parameter to a method in C++将函数作为参数传递给 C++ 中的方法
【发布时间】:2013-03-18 15:54:31
【问题描述】:

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

我的代码:

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

【问题讨论】:

  • 您没有将函数传递给applyProcessOnAll,而是在使用3 调用时传递了addOne 的返回值。

标签: c++ oop class parameters function-pointers


【解决方案1】:

因为您的 float (*g)() 不带参数,而您的 addOnefloat 参数。将你的函数指针更改为float (*g)(float),现在它应该可以工作了。

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

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

【讨论】:

    【解决方案2】:

    你有两个问题。

    第一个是Tony The Lion 指出的:您指定该函数不应接受任何参数,但您正在使用一个接受单个参数的函数。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-13
      • 2011-08-18
      • 2013-01-27
      • 2015-06-09
      • 2015-12-23
      • 1970-01-01
      • 2021-09-15
      相关资源
      最近更新 更多