我想为(数学)矩阵类创建一个方法,以使用参数中给定的函数处理对象,但我受困于函数指针!
我的代码:
#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/