Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

code :

#include <iostream>
using namespace std;
class golu
{
   int i;
public:
   void man()
   {
      cout<<"
try to learn 
";
   }
};
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.

my question are following :

  1. What I'm doing wrong in this code ?
  2. How to make object pointer ?
  3. How to make pointer to member function of a class and how to use them ?

Please explain me these concept.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
205 views
Welcome To Ask or Share your Answers For Others

1 Answer

Two errors corrected here:

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

   n=&m;
   (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)();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...