0

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

我的代码:

#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 ( )()'</p>

谢谢您的帮助!

现在它起作用了!谢谢!

改装件

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

2 回答 2

2

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

此外,您应该将函数分配给指针,而不是调用它。

A.applyProcessOnAll(&addOne, 3); //add args argument to `applyProcessOnAll` so you can call `g(arg)` inside.
于 2013-03-18T15:56:54.987 回答
0

你有两个问题。

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

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

于 2013-03-18T16:01:01.380 回答