在c++中将函数作为参数传递给方法
Passing a function as a parameter to a method in 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...rn";
Matrix A = Matrix(10,10);
A.setItem(3.141,10,10);
A.applyProcessOnAll(addOne(3));
cout << A.getItem(10,10);
cout << "rn";
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.
你有两个问题
第一个是Tony The Lion指出的:你指定函数不应该接受任何参数,但是你使用了一个只接受一个参数的函数。
第二个是你用函数调用的结果来调用applyProcessOnAll
,而不是指向函数的指针。
相关文章:
- 将成员函数指针作为参数传递给模板方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 如何将带有参数的方法传递给线程以执行?
- 在C++中传递数组作为函数参数的方法
- 将带有模板化方法的类作为带有GCC的模板参数传递
- 将派生类作为参数传递给方法,该方法是具有智能指针的基类
- 将私有数据成员作为默认参数传递给该类的公共方法时出错
- 如何将提升回调作为参数传递给方法?
- 将方法作为模板化参数传递 C++11
- 将 std::ofstream 对象作为参数传递给类方法
- 将给定的 vararg 参数传递给另一个函数的适当方法是什么?
- 将指针类方法作为参数传递给其他类方法C
- 如何将基类方法超载作为参数传递到C 中的模板类
- 将非静态数据成员作为默认参数传递给方法
- 将数组作为函数参数传递,并在其上调用开始/结束方法
- 将对象数组作为参数传递的最佳方法是什么
- 将参数传递给模板函数的方法
- 基本C - 构造contaning对象引用,并将其作为方法参数传递
- C++ "Best"参数传递方法