c ++成员函数指针问题

Gol*_*olu 9 c++ member-function-pointers

我是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();
}
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

我的问题如下:

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

请解释我这些概念.

APr*_*mer 8

这里纠正了两个错误:

int main()
{
   golu m, *n;
   void (golu::*t)() =&golu::man; 

   n=&m;
   (n->*t)();
}
Run Code Online (Sandbox Code Playgroud)
  1. 你想要一个指向函数的指针
  2. 运营商的优先级不是你期望的那个,我不得不添加括号.n->*t();被解释为(n->*(t()))你想要的(n->*t)();


Xeo*_*Xeo 5

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

R (C::*Name)(Args...)
Run Code Online (Sandbox Code Playgroud)

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

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

void (golu::*t)() = &golu::man;
Run Code Online (Sandbox Code Playgroud)

注意()成员函数之后的缺失。那将尝试调用您刚刚获得的成员函数指针,如果没有对象,那是不可能的。
现在,使用简单的typedef可以使它更具可读性:

typedef void (golu::*golu_memfun)();
golu_memfun t = &golu::man;
Run Code Online (Sandbox Code Playgroud)

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

golu m;
typedef void (golu::*golu_memfun)();
golu_memfun t = &golu::man;
(m.*t)();
Run Code Online (Sandbox Code Playgroud)

括号是重要的,因为()运营商(函数调用)具有更高的优先级(也称为优先级比).*(和->*)运营商。