2011-06-07 166 views
7

我是新来的C++。我想知道对象指针和成员函数的指针。我写了这以下代码: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. 如何使指针指向一个类的成员函数以及如何使用它们?

请给我解释一下这些概念。

回答

8

两个错误纠正在这里:

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

    n=&m; 
    (n->*t)(); 
} 
  1. 你想有一个函数指针
  2. 运营商的优先级是不是你所期望的一个我不得不加括号。 n->*t();被解释为(n->*(t())),而您想要(n->*t)();
+0

将您简要介绍一下先决?我不了解这方面的优先权概念。 – Golu 2011-06-07 08:53:36

+0

是否修改回答适合你? – AProgrammer 2011-06-07 08:56:48

+0

请告诉我先决。 – Golu 2011-06-07 09:15:48

2

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

+0

@xeo纠正了。 – Ali1S232 2011-06-07 08:52:47

1

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

(2)你应该声明这样的:

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

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

4

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

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

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