如何将一个类的函数作为参数传递给同一类的另一个函数
我基本上想使用 diff 函数来提取类(ac)的不同元素。
代码与此类似:
.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); // original and incorrect
return f0(ac,&Myclass::f1); //solved the problem
}
但是,我有另一个错误:
std::cout << f1(ac);
^ error: expression must have (pointer-to-) function type
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看看错误点在哪里。我敢打赌它不在函数声明行上,而是在你如何调用它上。
观察:
您收到错误是因为您错误地调用了该函数。鉴于上面的
foo
,我们知道这行不通:因为
baz
需要调用一个实例。你需要给它一个(我假设this
):语法有点奇怪,但是这个运算符
->*
说:“获取成员函数指针右边的实例,并用左边的实例来调用它。” (还有一个.*
运算符。)Look at where the error points. I bet it's not on the function declaration line, but on how you call it.
Observe:
You're getting your error because you're calling the function incorrectly. Given my
foo
above, we know this won't work:Because
baz
requires an instance to be called on. You need to give it one (I'll assumethis
):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.)您仍然没有发布创建指向成员的指针的代码,这似乎是错误的原因,但是您如何使用它存在问题。
要使用指向成员的指针,您需要使用
->*
或.*
运算符之一以及对该类的适当实例的指针或引用。例如:您可以像这样调用函数:
请注意,对于指向成员的指针,您需要
&
,这与隐式转换为函数指针的普通函数名称不同。You still haven't posted the code where you create the pointer to member which is what the error seems to be about, but there is an issue with how you use it.
To use a pointer to member you need to use one of
->*
or.*
operators with a pointer or reference to an appropriate instance of the class. E.g.:You can call the function like so:
Note that for pointers to members you need
&
, unlike normal function names which convert implicitly to function pointers.