将函数作为参数传递给C++中的方法
问题描述:
我想为(数学)矩阵类使用参数中给出的函数处理对象的方法,但我被卡在函数指针中!将函数作为参数传递给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(浮动)' 注意到没有匹配函数void矩阵:: applyProcessOnAll(浮点()()) 注:为参数1从 '浮动' 没有已知的转换 '浮动()()'
感谢您的帮助!
现在它的工作!谢谢!
改装件
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.
+1
谢谢!有效! – 2013-03-18 16:05:20
答
您有两个问题。
第一个是Tony The Lion指出的那个:你指定该函数不应该带任何参数,但是你正在使用一个只带一个参数的函数。
第二个是你打电话applyProcessOnAll
带有函数调用的结果,而不是指向函数的指针。
您没有将函数传递给'applyProcessOnAll',您在用'3'调用时传递'addOne'的返回值。 – enobayram 2013-03-18 15:57:00