C++ gets the function pointer details and instance code for the member functions of the class
- 2020-05-17 05:56:25
- OfStack
C++ gets the function pointer of the member function of the class
So let's do that in 1 actual code.
class A
{
public:
staticvoid staticmember(){cout<<"static"<<endl;} //static member
void nonstatic(){cout<<"nonstatic"<<endl;} //nonstatic member
virtualvoid virtualmember(){cout<<"virtual"<<endl;};//virtual member
};
int main()
{
A a;
//static A member function , Gets the actual address of the function in memory, and because static The member is global, so it cannot be used A:: qualifiers
void(*ptrstatic)()=&A::staticmember;
//nonstatic A member function Gets the actual address of the function in memory
void(A::*ptrnonstatic)()=&A::nonstatic;
// The virtual function takes the offset value from the virtual function table, which guarantees the same polymorphic effect when called over the pointer
void(A::*ptrvirtual)()=&A::virtualmember;
// How function Pointers are used
ptrstatic();
(a.*ptrnonstatic)();
(a.*ptrvirtual)();
}
Refer to section 1 ~ of C++ Primer (3rd), page 532, 13.6 Pointers to class members
1.1 Pointers to external functions are declared as:
void(*pf)(char*,constchar*);
void strcpy(char* dest,constchar* source);
pf=strcpy;
2.1 Pointers to class A member functions are declared as follows:
void(A::*pmf)(char*,constchar*);
pmf is a pointer to an A member function, which returns an untyped value. The function takes two arguments, the types of which are char * and const char *. Except for adding A:: before the asterisk, which is the same as declaring Pointers to external functions.
3. The way to assign a value to a member pointer is to assign the function name to the pointer through the pointer symbol &.
As follows:
class A
{
public:
void strcpy(char*,constchar*);
void strcat(char*,constchar*);
};
pmf =&A::strcpy;
Thank you for reading, I hope to help you, thank you for your support of this site!