【问题标题】:c++ member function pointer problemc++成员函数指针问题
【发布时间】:2011-09-09 21:37:19
【问题描述】:

我是 c++ 新手。我想了解对象指针和指向成员函数的指针。我写了如下代码:

代码:

#include <iostream>
using namespace std;
class golu
{
   int i;
public:
   void man()
   {
      cout<<"\ntry to learn \n";
   }
};
int main()
{
   golu m, *n;
   void golu:: *t =&golu::man(); //making pointer to member function

   n=&m;//confused is it object pointer
   n->*t();
}

但是当我编译它时,它显示了两个错误:

pcc.cpp: In function ‘int main()’:
pcc.cpp:15: error: cannot declare pointer to ‘void’ member
pcc.cpp:15: error: cannot call member function ‘void golu::man()’ without object
pcc.cpp:18: error: ‘t’ cannot be used as a function.

我的问题如下:

  1. 我在这段代码中做错了什么?
  2. 如何制作对象指针?
  3. 如何制作指向类的成员函数的指针以及如何使用它们?

请解释一下这些概念。

【问题讨论】:

    标签: c++ member-function-pointers


    【解决方案1】:

    这里纠正了两个错误:

    int main()
    {
       golu m, *n;
       void (golu::*t)() =&golu::man; 
    
       n=&m;
       (n->*t)();
    }
    
    1. 你想要一个指向函数的指针
    2. 运算符的优先级不是你所期望的,我不得不加上括号。 n-&gt;*t(); 被解释为 (n-&gt;*(t())) 而你想要 (n-&gt;*t)();

    【讨论】:

    • 您能解释一下优先权吗?在这种情况下,我不明白优先级的概念。
    • 修改后的答案适合你吗?
    • 这就是让您认为 1 + 2 * 3 是 7 而不是 9 的原因。请参阅 en.wikipedia.org/wiki/Order_of_operations
    【解决方案2】:

    成员函数指针的形式如下:

    R (C::*Name)(Args...)
    

    其中R 是返回类型,C 是类类型,Args... 是函数的任何可能参数(或无参数)。

    有了这些知识,您的指针应该如下所示:

    void (golu::*t)() = &golu::man;
    

    注意成员函数后面缺少的()。这将尝试调用您刚刚获得的成员函数指针,如果没有对象,这是不可能的。
    现在,使用简单的 typedef 就变得更加可读了:

    typedef void (golu::*golu_memfun)();
    golu_memfun t = &golu::man;
    

    最后,使用成员函数不需要指向对象的指针,但需要括号:

    golu m;
    typedef void (golu::*golu_memfun)();
    golu_memfun t = &golu::man;
    (m.*t)();
    

    括号很重要,因为() 运算符(函数调用)比.*(和-&gt;*)运算符具有更高的优先级(也称为precedence)。

    【讨论】:

      【解决方案3】:

      'void golu:: *t =&golu::man();'应更改为 'void (golu:: *t)() =&golu::man;'您正在尝试使用指向函数的指针而不是指向静态函数结果的指针!

      【讨论】:

        【解决方案4】:

        (1) 函数指针未正确声明。

        (2) 你应该这样声明:

        void (golu::*t) () = &golu::man;
        

        (3) 成员函数指针应与class的对象一起使用。

        【讨论】: