Ask THE C ++ Pro 10-Minute Solution (2)

zhaozj2021-02-17  53

Ask THE C Pro 10-Minute Solution

Pointing to clasmen

I'VE Received a Lot of Questions Lately Such AS This About Pointers to Class Methods: "I Work with Visual C 4.0. I cannot USE The Pointer of a class method. The compiration error message is:

Cannot Convert Parameter 2 from 'long (unsigned long)' to 'long (__cdecl *) (unsigned long)' What shop i do? "

Here is The code for one way to solid this problem.

// in the header

Class Ckernel:

{

Long (* lpfunc) (DWORD);

Long Olesendtc (DWORD DWInfo);

}

// in the CPP file

Bool ckernel :: init ()

{

LPFUNC = OLESENDTC;

Return True;

}

Class methods all have one hidden argument, a pointer to the class object the method is called on. C uses this pointer to find the location of any class data that the method may reference. If you try and use a standard function pointer to call a Class Method, C Has No Way To Pass this Hidden Argument and a conflict results.

To help deal with this and to improve type safety, C added three new operators, :: *, *, and -.> *, To allow for safe pointers to members These pointers to members can point to either member functions or variables..

Class Ctest

{

PUBLIC:

BOOL init ();

Long Olesendtc (DWORD DWInfo);

}

Long (ctest :: * lpfunc) (DWORD DWINFO) = & ctest :: Olesendtc;

int main ()

{

CTEST TEST;

(TEST. * lpfunc) (0);

Return 0;

}

Long ctest :: OlesendTc (DWORD DWInfo)

{

COUT << "in Oleseendtc / N";

Return 0;

}

This example shows one use of pointers to members. The code uses the :: * operator to declare lpFunc as a pointer to a CTest member function. Note that, rather than assign a value to this pointer at run time, the pointer is simply initialized In the declaration.in the main function, this example uses the. * Operator to call the method Pointed to by lpfunc. if Test WERE A Pointer Here, You 10 Uses -> * Operator Instead.

C HAS a Lot of Things Going On Under The Hood Such AS Hidden Arguments to Methods. Pointers to Members Allow You to Safely Declare a Pointer To Safely Declare a Pointer To a class method and call method.

转载请注明原文地址:https://www.9cbs.com/read-30089.html

New Post(0)