9

我是 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. 如何使指向类的成员函数的指针以及如何使用它们?

请解释我这些概念。

4

4 回答 4

8

这里更正了两个错误:

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

   n=&m;
   (n->*t)();
}
  1. 你想要一个指向函数的指针
  2. 运算符的优先级不是您所期望的,我不得不添加括号。n->*t();被解释为(n->*(t()))你想要的时候(n->*t)()
于 2011-06-07T08:49:27.460 回答
5

成员函数指针具有以下形式:

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)();

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

于 2011-06-07T08:50:22.597 回答
2

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

于 2011-06-07T08:46:32.000 回答
1

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

(2) 你应该这样声明:

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

(3) 成员函数指针应与class.

于 2011-06-07T08:48:41.290 回答