Detailed explanation of object pointer and object array _c language in C + +

Source: Internet
Author: User

C + + Object pointers
Pointer to Object

When an object is created, the compilation system allocates a certain amount of storage space for each object to store its members. The starting address of the object space is the pointer to the object. You can define a pointer variable that holds a pointer to an object.

If there is a class:

Class time
{public
  :
  int hour;
  int minute;
  int sec;
  void Get_time ();
void Time::get_time ()
{
  cout< 
 

On this basis there are the following statements:

  Time *pt; Define PT as pointer variable time T1 to object of time class
  ;//define T1 for Time class object
  pt=&t1;//Assign T1 start address to PT


In this way, PT is a pointer variable pointing to the Time class object, which points to the object T1.

The general form of a pointer variable that defines a class object is:

  Class Name * object pointer name;

You can access objects and members of objects through object pointers. Such as:

  The  object that the *pt//pt points to, that is, T1
  (*pt). Hour member of the object to which//pt is pointing, that is, the hour member of the
  object to which you are pointing, that is T1.hour pt->hour
  (*PT). Get_time ()  //Call the Get_time function in the object to which the PT points, that is, T1.get_time
  pt->get_time ()//calling the Get_time function in the object to which the PT points, namely T1.get_time

The 2nd, 3 lines are equivalent, and the 4th and 52 lines are equivalent.
Pointer to object member

Object has an address, and a pointer variable that holds the initial address of the object is a pointer variable that points to the object. The member of the object has an address, and a pointer variable that holds the member address of the object is a pointer variable that points to the member of the object.

1 pointer to object data member
The method that defines a pointer variable that points to an object data member is the same as the method that defines a pointer variable to a generic variable. For example:

  int *p1; Defines a pointer variable that points to an integral type of data


The general form of a pointer variable that defines a member of an object data is:

  Data type name * pointer variable name;


If the data member of the time class is hour to the public integer data, you can access the object data member hour outside the class by pointing to the pointer variable of the object data member:

  p1=&t1.hour; Assigns the address of the data member hour of the object T1 to the P1,P1 value that points to t1.hour
  cout<<*p1<<endl;//Output T1.hour

2 pointer to an object member function
Notice to the reader that the method that defines a pointer variable that points to an object member function differs from the method that defines a pointer variable that points to a normal function. Here's a recap of a pointer variable that points to a normal function:
Data type name (* pointer variable name) (Parameter table column);
Such as
void (*p) (); P is a pointer variable that points to a void type function
You can point it to a function and call the function through the pointer variable:
p = fun; Pass the population address of the fun function to the pointer the p,p is pointing to the function fn
(*p)  ( ); Invoke the FN function

It is more complex to define a pointer variable that points to an object member function. If you imitate the above method, assign the name of the object member function to the pointer to the top p:

  p = t1.get_time;


A compilation error occurs. Why, then?

A member function has one of the most fundamental differences from a normal function: It is a member of a class. The compilation system requires that in the above assignment statement, the type of the pointer variable must match the type of the right-hand function of the assignment number, and the requirements are matched in the following 3 ways:
The type and number of parameters of ① function parameters;
The type of the ② function return value;
The class to which the ③ belongs.

Now at 3 points, the ①② two points are matched, and the ③ points do not match. The pointer variable p is independent of the class, and the face get_ time function belongs to the time class. Therefore, to distinguish between ordinary functions and the different properties of member functions, it is not possible to invoke member functions directly by using member function names as function entry addresses outside the class.

So how do you define pointer variables that point to member functions? The following form should be used:

  void (time::* p2) (); Defines p2 as a pointer variable that points to a public member function in the time class


Note: The brackets on either side of (time:: *P2) cannot be omitted because () has a higher precedence than *. If you do not have this bracket, it is equivalent to:

  void time::* (P2 ())//This is a function that returns a void pointer

The general form that defines a pointer variable that points to a public member function is:

  Data type name (class name::* pointer variable name) (Parameter table column);

You can have it point to a common member function by assigning the entry address of the public member function to a pointer variable that points to a public member function. Such as:

  p2=&time::get_time;


The general form of the pointer variable pointing to a common member function is

  Pointer variable name =& class name:: Name of member function;


In the VC + + system, you can not write and, in accordance with the use of C language, but it is recommended to write C + + programs do not omit &.

[Example] about how object pointers are used.

#include <iostream>
using namespace std;
Class time
{public
  : Time
  (int,int,int);
  int hour;
  int minute;
  int sec;
  void Get_time ();
Time::time (int h,int m,int s)
{
  hour=h;
  minute=m;
  sec=s;
}
void Time::get_time ()//declaring public member functions
//Defining public member functions
{
  cout< 
 

The result of the program running is:

Ten (output of line 4th of main function) 10:13:56 (output of line
5th of main function) 10:13:56 (output of row
7th of main function)
10:13:56 (output of main function 10th row)


You can see that in order to output the Hour,minute and SEC values in T1, you can use 3 different methods.

A few notes:
1 from the main function of the 9th line, you can see that the entry address of the member function is correctly written:

  & Class Name:: member function name


Should not be written as:

  P3 =&t1.get_time; T1 As Object name

A member function is not stored in the object's space, but in space outside the object. If you have multiple objects of the same class, they share the same function code snippet. Therefore, the P3 to the pointer variable should be the entry address of this common function code snippet.

The Get_time function that calls T1 can be in the form of T1.get_time (), which is logically a member function that can be invoked through the object name. Now the address is needed in the program statement, which is physical, and the specific address is associated with the class rather than the object.

2 The main function 8th, 92 lines can be written together as a line:

  void (time::* p3) () =&time::get_time; When defining a pointer variable, specify its pointing

C + + Object array
Arrays can consist not only of simple variables (for example, every element of an integer array is an integer variable), but also of objects (each element of an object array is a homogeneous object).

In daily life, there are many entities of the attributes are common, but the specific content of the attributes are different. For example, there are 50 students in a class, and each student's attributes include name, sex, age, grade, etc. If you create an object for each student, you need to take 50 object names, respectively. It is inconvenient to process the program. You can define a "student Class" Object array, and each array element is a student class object. For example

  Student STUD[50]; Suppose you have declared the student class, define the stud array, and have 50 elements


When you create an array, you also call the constructor. If you have 50 elements, you need to call 50 constructors.

You can provide an argument when you define an array when you want it to implement initialization. If the constructor has only one argument, you can provide the argument directly within the curly braces following the equal sign when defining the array. Such as

 Student stud[3]={60,70,78}; Valid, 3 arguments passed to the constructor of 3 array elements, respectively


If the constructor has more than one argument, you cannot use a method that provides all the arguments directly when you define the array. Because an array has multiple elements, to provide multiple arguments for each element, and if the constructor has a default parameter, it is easy to make the corresponding relationship between the real participation parameter ambiguous and ambiguity. For example, a class student constructor has multiple parameters and is the default parameter:

Student:: Student (INT=1001,INT=18,INT=60); Define constructors, with multiple parameters, and default parameters


If the statement that defines an array of objects is

  Student stud[3]={1005,60,70};


It is best not to use this method of ambiguity in the program.

The compilation system only passes an argument to the constructor of each object element, so the number of arguments provided when defining an array cannot exceed the number of array elements, as

  Student stud[3]={60,70,78,45}; Not valid, the number of arguments exceeds the number of elements in the object array


So, if the constructor has more than one argument, how do you initialize it when you define an array of objects? The answer is: write out the constructor and specify the argument in curly braces, respectively.

If the constructor has 3 parameters, it represents the school number, age, and grade. You can define an array of objects like this:

Student stud[3]={//Defines the object array
  Student (1001,18,87),//invokes the constructor of the 1th element, provides it with 3 argument
  Student (1002,19,76),// Invokes the constructor of the 2nd element, providing it with 3 argument
  Student (1003,18,72)//Calling the constructor of the 3rd element, providing it with 3 arguments
};

When an array of objects is established, the constructor is called separately and initialized for each element. The arguments for each element are wrapped in parentheses, and the corresponding set of parameters for the constructor is not confused.

An example of how an array of objects is used.

#include <iostream>
using namespace std;
Class Box
{public
:
  //Declare a constructor with default parameters, initialize the data member with the Parameter initialization table
  box (int h=10,int w=12,int len=15): Height (h), Width (w), Length (len) {}
  int volume ();
Private:
  int height;
  int width;
  int length;
};
int Box::volume ()
{return
  (height*width*length);
}
int main ()
{
  box a[3]={//Definition Object array
   box (10,12,15),//Call constructor box, provide the 1th element's argument
   box (15,18,20),// Call constructor box to provide the 2nd element's argument
   box (16,20,26)//Call constructor box to provide an argument for the 3rd element
  ;
  cout<< "Volume of a[0] is" <<a[0].volume () <<endl;
  cout<< "Volume of a[1] is" <<a[1].volume () <<endl;
  cout<< "Volume of a[2] is" <<a[2].volume () <<endl;
  return 0;
}

The results of the operation are as follows:

Volume of a[0] is 1800
volume The a[1] is 5400
volume of a[2] is 8320

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.