C++ pointer to object
When C++ creates an object, the compilation system will allocate a certain amount of storage space for each object to store its members. The starting address of the object space is the pointer of the object. You can define a pointer variable to store the pointer of the object.
The general form of defining a pointer variable pointing to a class object is
Class name * object pointer name;
Objects and their members can be accessed through object pointers
C++ pointer to object member
In C++, objects have addresses. The pointer variable that stores the initial address of the object is the pointer variable pointing to the object. The members in the object also have addresses. The pointer variable that stores the address of the object member is the pointer variable that points to the object member.
1. Pointer to object data member
The method of defining pointer variables pointing to object data members is the same as defining pointer variables pointing to ordinary variables.
Data pointer variable definition The general form of a pointer variable pointing to an object's data member is:
Data type name * pointer variable name;
2. Pointer to object member function
The method of defining pointer variables pointing to object member functions in C++ is different from the method of defining pointer variables pointing to ordinary functions.
There is one biggest difference between member functions and ordinary functions: a member function is a member of a class.
The general form of defining a pointer variable pointing to a public member function is
Data type name (class name ∷ * pointer variable name) (parameter list column);
The general form of a pointer variable pointing to a public member function is
Pointer variable name = & class name ∷ member function name;
Case: Use of C++ object pointers
#include <iostream>
using namespace std;
class Time
{ public:Time(int,int,int); int hour,minute,second; void getTime(); //Declare member function }; Time::Time(int h, int m,int s) { hour=h; minute=m; second=s; } void Time::getTime()//Define member function { cout<<hour<<"point"<<minute<<"minute" <<second<<"second"<<endl; } int main( )// Main function of the program { Time time(20,22,45); //Define Time class object time time.getTime(); //Call Function // Define the pointer variable point pointing to integer data and point to time.hour int *point=&time.hour; cout<<*point<<endl; return 0; }
Compile and run results:
20:22:45:
20
--------------------------------
Process exited after 0.07195 seconds with return value 0
Please press Press any key to continue. . .