如何将一个类的函数作为参数传递给同一类的另一个函数

编程入门 行业动态 更新时间:2024-10-10 08:25:04
本文介绍了如何将一个类的函数作为参数传递给同一类的另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我基本上想使用dif函数提取类(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); //原始且不正确的返回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.)

更多推荐

如何将一个类的函数作为参数传递给同一类的另一个函数

本文发布于:2023-10-12 16:24:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1485265.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   如何将   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!