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

标签 c++ oop class parameters function-pointers

我想为(数学)矩阵类创建一个方法,以使用参数中给定的函数处理对象,但我受困于函数指针!

我的代码:

#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.

关于c++ - 将函数作为参数传递给 C++ 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15481165/

相关文章:

c++ - 可移植 fstream 文件路径的正确语法是什么?

c# - 在彼此中实例化两个类中的每一个

Java 泛型 : why someObject. getClass() 不返回 Class<?延伸 T>?

c++ - 两个线程使用相同的 websocket 句柄——这会导致任何问题吗?

c++ - 运行时错误 (SIGABRT) - SPOJ

php - 使用 mysql 执行许多查询是否可以,还是我应该寻求优化?

c# - 将对公共(public) setter 的访问限制为特定对象 (C#)

php - 什么是回调函数以及如何将它与 OOP 一起使用

javascript - 警告 : Accessing reactClass via the main React package is deprecated

c++ - COM 初始化和在 Win32 C++ DLL 中的使用