代码类似于以下代码:
.h:
class MyClass { public: double f1(AnotherClass&); void MyClass :: f0(AnotherClass& ac,double(MyClass :: * f1)(AnotherClass&)); };.cc:
double MyClass :: f1(AnotherClass& ac) { return ac.value; } void MyClass :: f0(AnotherClass& ac,double(MyClass :: * f1)(AnotherClass&)) { std :: cout<< f1(ac); }不起作用,它给出错误#547采用非标准格式成员函数的地址
编辑:
我从以下方式调用它:
void MyClass(AnotherClass& ac) { return f0(ac,&f1); //原始且不正确的返回f0(ac,& Myclass :: f1); //解决了问题}但是,我还有另一个错误:
std :: cout<< f1(ac); ^错误:表达式必须具有(指向指针的)函数类型解决方案
查看错误的位置。我敢打赌,它不在函数声明行上,而是在调用它的方式上。
观察:
struct foo { void bar(void(foo :: * func)(void)); void baz(void) { bar(& foo :: baz); //注意地址的获取方式 bar(& baz); //这是错误的} };
由于您在错误地调用该函数。鉴于以上我的 foo ,我们知道这行不通: baz(); // foo ::去哪里了?
因为 baz 需要调用一个实例上。您需要给它一个(我假设 this ):
std :: cout<< (this-> * f1)(ac);语法有点怪异,但此运算符-> * 说:取右边的成员函数指针,并用左边的实例调用它。 (还有一个。* 运算符。)
i basically want to use a dif function to extract a different element of a class (ac).
the code is similar to this:
.h:
class MyClass { public: double f1(AnotherClass &); void MyClass::f0(AnotherClass & ac, double(MyClass::*f1)(AnotherClass &)); };.cc:
double MyClass::f1(AnotherClass & ac) { return ac.value; } void MyClass::f0(AnotherClass & ac, double(MyClass::*f1)(AnotherClass &)) { std::cout << f1(ac); }didn't work, it gives error#547 "nonstandard form for taking the address of a member function"
EDIT:
I call it from:
void MyClass(AnotherClass & ac) { return f0(ac,&f1); // original and incorrect return f0(ac,&Myclass::f1); //solved the problem }However, I have another error:
std::cout << f1(ac); ^ error: expression must have (pointer-to-) function type解决方案
Look at where the error points. I bet it's not on the function declaration line, but on how you call it.
Observe:
struct foo { void bar(void (foo::*func)(void)); void baz(void) { bar(&foo::baz); // note how the address is taken bar(&baz); // this is wrong } };
You're getting your error because you're calling the function incorrectly. Given my foo above, we know this won't work:
baz(); // where did the foo:: go?Because baz requires an instance to be called on. You need to give it one (I'll assume this):
std::cout << (this->*f1)(ac);The syntax is a bit weird, but this operator ->* says: "take the member function pointer on the right, and call it with the instance on the left." (There is also a .* operator.)
更多推荐
如何将一个类的函数作为参数传递给同一类的另一个函数
发布评论