我想将类A的成员函数作为参数传递给全局函数。我该做些什么才能做到这一点?另外,这是一个好主意吗?上下文:我想这样做是因为(同义词)doSomething(...)
是一个非常通用的函数,用于main()
以及不同的类。因此,我可以避免在项目中有相同代码的多个副本。什么是替代品(如果它不是最佳的)?将类成员函数作为参数传递给全局函数
#include <iostream>
using namespace std;
double doSomething(int i, double (*f)(double)) { return (*f)(i); }
class A{
public:
A(double x) : number(x) {}
double times(double i) { return ::doSomething(i, &A::multiply);} //calles the global function and gives a member function as parameter
double multiply(double i) {return number*i;}
private:
double number;
};
int main() {
A obj(5.0);
cout << obj.times(3.5) <<endl;
return 0;
}
编译器抱怨:
../src/test5.cpp: In member function ‘double A::times(double)’:
../src/test5.cpp:17:63: error: cannot convert ‘double (A::*)(double)’ to ‘double (*)(double)’ for argument ‘2’ to ‘double doSomething(int, double (*)(double))’
double times(double i) { return ::doSomething(i, &A::multiply);} //calles the global function and gives a parameter member function as parameter
^
../src/test5.cpp:17:65: warning: control reaches end of non-void function [-Wreturn-type]
double times(double i) { return ::doSomething(i, &A::multiply);} //calles the global function and gives a parameter member function as parameter
在你的榜样,我会仍然需要declair对象的类型'doSomething'希望。这意味着我仍然需要其他对象的相同代码的副本。我认为Wojtek Surowka重新考虑我的设计是正确的。谢谢您的回答。 – dani