c++成员函数指针问题

标签 c++ pointer-to-member

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

请解释一下这些概念。

最佳答案

这里纠正了两个错误:

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

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

关于c++成员函数指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46920830/

相关文章:

c++ - 尽量避免重复调用一个函数

c++ - 如何将 const 成员函数作为非常量成员函数传递

c++ - 具有包含另一个类的函数指针的映射的类

c++ - 错误 : cannot convert 'void (CApp::*)()' to 'void (*)()' for argument '1' to 'void Mix_HookMusicFinished(void (*)())'

c++ - 将指针从派生类方法转换为基类

c++ - std::function 无法区分重载函数

c++ - 为什么 C++ 中的无限指针链不会导致内存爆炸?

c++ - 在遍历多个集合时写回迭代器

c++ - MFC-CArray 复制

C++同时输入输出到控制台窗口