我是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.我的问题如下:
请解释一下这些概念。
发布于 2011-06-07 08:49:27
在此更正了两个错误:
int main()
{
golu m, *n;
void (golu::*t)() =&golu::man;
n=&m;
(n->*t)();
}n->*t();被解释为(n->*(t())),而您想要(n->*t)();发布于 2011-06-07 08:50:22
成员函数指针具有以下形式:
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)();括号很重要,因为()运算符(函数调用)比.* (和->*)操作符具有更高的优先级(也称为优先)。
发布于 2011-06-07 08:46:32
'void::*t =& golu::man();‘应该改为'void (golu::*t)() () =&golu::man;’您尝试使用指针来实现函数,而不是指向静态函数的结果!
https://stackoverflow.com/questions/6262712
复制相似问题