Home > Back-end >  Pointer to the class member functions cannot be explicitly call outside the class (C)
Pointer to the class member functions cannot be explicitly call outside the class (C)

Time:11-19

Today when writing the c + + program meets a strange question, complete have no way to explain, also is a class member function pointer cannot be explicitly call outside the class,
A bit around the mouth, the code is as follows:
The class header file node. H

 
#include
#include

The class node.
Typedef double (pf) node: : * (double x);

The class node
{
Public:
The node ();
~ the node ();
Double func1 (double x);
Pf p;
Double fp (double x);
Private:

};


Class of source node. CPP

 
# include "node. H"

Node: : node ()
{
P=& amp; Node: : func1;
}

Node: : ~ node ()
{
}

Double node: : func1 (double x)
{
STD: : cout & lt; <"Func1:" & lt; return 1;
}

Double node: : fp (double x)
{
Return (this - & gt; * p) (x);
}


Call the main function of the file. The main CPP

 
# include "node. H"

Int main ()
{
The node A;
Double x=1.0;
Amy polumbo (x);//error1
A. * p (x);//error2
* (Amy polumbo) (x);//error3
A.f p (x);//correct;
return 1;
}

Cause analysis:
There is no find the reason,
Define a member function pointer to a class member function, but on the outside the class function through the pointer in the calling class member functions, all three of these calls were through the compilation,

CodePudding user response:

A member function automatically bind a this pointer parameter, so that it's wrong to define a function pointer,

CodePudding user response:

(a. * (Amy polumbo)) (x);//error2

CodePudding user response:

Pointer to a class member function is equivalent to an offset, also known as p func is equal to the offset of the node class
So can't directly call p (x) way, and want to use A. * p (x)
But since p is a member of the node, class non-static member must be combined with the class object to determine,
Like the class A members have an int x, you can't direct x=10; But to A, a1. A1. X=10;
In the same way your p is also a member of the node to access it, need to Amy polumbo
So the following
(a. * (Amy polumbo)) (x) method calls
  • Related