C ++成员函数指针问题 [英] c++ member function pointer problem

查看:199
本文介绍了C ++成员函数指针问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是c ++的新手。我想了解对象指针和成员函数指针。我写了下面的代码:

I'm new to c++ . I want to know about object pointer and pointer to member function . I wrote a code which is following:

代码:

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

但是当我编译它时,它向我显示了以下两个错误:

but when i compile it it shows me two error which is following:

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

请向我解释这些概念。

推荐答案

在此处更正了两个错误:

Two errors corrected here:

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

   n=&m;
   (n->*t)();
}




  1. 您想要一个函数指针

  2. 运算符的优先级不是您期望的优先级,我必须加上括号。 n-> * t(); 解释为(n-> *(t()))而你想(n-> * t)();

  1. you want a pointer to function
  2. the priority of the operators is not the one you expected, I had to add parenthesis. n->*t(); is interpreted as (n->*(t())) while you want (n->*t)();

这篇关于C ++成员函数指针问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆