我是 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.
我的问题如下:
- 我在这段代码中做错了什么?
- 如何制作对象指针?
- 如何制作指向类成员函数的指针以及如何使用它们?
请解释一下这些概念。
最佳答案
这里纠正了两个错误:
int main()
{
golu m, *n;
void (golu::*t)() =&golu::man;
n=&m;
(n->*t)();
}
- 你想要一个指向函数的指针
- 运算符的优先级不是您期望的,我不得不添加括号。
n->*t();
被解释为(n->*(t()))
而你想要(n->*t)( )
;
关于c++成员函数指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46920830/