Apr 20, 2013 at 7:42pm UTC
In this Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include <iostream>
using namespace std;
class Data
{
private :
int y;
static int x;
public :
void SetData(int value) {y = value; return ;};
int GetData() {return y;};
static void SSetData(int value) {x = value; return ;};
static int SGetData() {return x;};
};
int Data::x = 0;
void main(void )
{
Data mydata, mydata2;
// Initialize pointer.
void (Data::*pmfnP)(int ) = &Data::SetData; // mydata.SetData;
// Initialize static pointer.
void (*psfnP)(int ) = &Data::SSetData;
mydata.SetData(5); // Set initial value for private data.
cout << "mydata.data = " << mydata.GetData() << endl;
(mydata.*pmfnP)(20); // Call member function through pointer.
cout << "mydata.data = " << mydata.GetData() << endl;
(mydata2.*pmfnP)(10) ; // Call member function through pointer.
cout << "mydata2.data = " << mydata2.GetData() << endl;
(*psfnP)(30) ; // Call static member function through pointer.
cout << "static data = " << Data::SGetData() << endl ;
}
On line 23 why is the scope resolution used in
void (Data::*pmfnP)(int )
and
&Data::SetData;
and on line 26
&Data::SSetData;
I am really confused? and what does the .* operator do? I found this code somewhere else out of my book so can someone please explain? Thanks!
And also pmfnP isnt even defined in the class so what does
Data::*pmfnP)(int )
do?
Last edited on Apr 20, 2013 at 7:51pm UTC
Apr 20, 2013 at 8:01pm UTC
It is a pointer to a member function.
Apr 20, 2013 at 8:04pm UTC
I know but I am confused on the use of ::
Apr 20, 2013 at 8:04pm UTC
and why you need Data:: in Data::*pmfnp) (int)
Apr 20, 2013 at 8:10pm UTC
¿How will you say that it is a pointer to member function of `Data' then?
Yes, the syntax is awful.
Remember the equivalence
1 2
void foo::bar(baz);
void bar(foo *this , baz);
Last edited on Apr 20, 2013 at 8:10pm UTC
Apr 20, 2013 at 8:13pm UTC
Can you reference me to a documentation or something more detailed please?
Apr 20, 2013 at 8:57pm UTC
So the :: just tells the compiler that it is a function pointer to that class? So I cant assign it to anything else other then a function of that class?
Apr 20, 2013 at 9:13pm UTC
Yes
It would be the same as
1 2 3 4
void (*function)(int ); //function pointer, receives int returns nothing
void foo(std::string);
function = &foo; //illegal
Last edited on Apr 20, 2013 at 9:14pm UTC