【问题标题】:Passing a function pointer to a member function in C++.Getting error将函数指针传递给 C++ 中的成员函数。出现错误
【发布时间】:2017-10-29 11:40:51
【问题描述】:

您好,这是我在 C++ 中传递函数指针的第一次体验。 所以这是我的代码:-

#include <iostream>
using namespace std;

// Two simple functions
class student
{
public:
void fun1() { printf("Fun1\n"); }
void fun2() { printf("Fun2\n"); }

// A function that receives a simple function
// as parameter and calls the function
void wrapper(void (*fun)())
{
    fun();
}
};

int main()
{   student s;

    s.wrapper(s.fun1());
    s.wrapper(s.fun2());
    return 0;
}

最初在包装函数中我只传递了 fun1 和 fun2。我得到了一个错误

try.cpp:22:15: error: ‘fun1’ was not declared in this scope
     s.wrapper(fun1);
               ^~~~
try.cpp:23:15: error: ‘fun2’ was not declared in this scope
     s.wrapper(fun2);

后来我尝试将 s.fun1() 和 s.fun2() 作为参数传递,但再次出错

try.cpp:23:23: error: invalid use of void expression
     s.wrapper(s.fun1());
                       ^
try.cpp:24:23: error: invalid use of void expression
     s.wrapper(s.fun2());

请帮助我不知道该怎么办:(

【问题讨论】:

标签: c++ oop pointers function-pointers member-function-pointers


【解决方案1】:

让我们处理帖子中的两个问题。

  1. 您正在呼叫fun1fun2。由于它们的返回类型是void,因此您不能将它们的结果作为某物的值传递。特别是作为函数指针的值。您也无法使用点成员访问运算符获取他们的地址。这将我们带到以下内容。

  2. 成员函数与常规函数不同。你不能只取他们的地址。它们的处理是特殊的,因为成员函数只能在对象上调用。所以它们有一个特殊的语法,涉及到它们所属的类。

这就是你将如何做你所追求的事情:

class student
{
public:
    void fun1() { printf("Fun1\n"); }
    void fun2() { printf("Fun2\n"); }

    // A function that receives a member function
    // as parameter and calls the function
    void wrapper(void (student::*fun)())
    {
        (this->*fun)();
    }
};

int main()
{   student s;

    s.wrapper(&student::fun1);
    s.wrapper(&student::fun2);
    return 0;
}

【讨论】:

  • Teller 如果 fun1 返回一些 int 怎么办,那么我应该如何编写 wrapper?我将 fun1 的返回值存储在 main 中的某个变量 x 中。
  • @codie - 然后修改代码以包含一些返回语句,就像使用常规函数指针一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-01
  • 2015-03-22
  • 1970-01-01
  • 2021-11-29
相关资源
最近更新 更多