Use of C ++ and objects (3). Use of Objects

Source: Internet
Author: User

Use of C ++ and objects (3). Use of Objects

  Object Array

If the constructor has only one parameter, it can be provided directly in curly brackets after the equal sign when defining an array. Student stud [3] = {90, 92, 01}; // valid

If the constructor has multiple parameters, it cannot be used to directly provide all the real parameters in the definition.

But it can be defined as follows:

// The constructor has three parameters: Student ID, age, score Student stud [3] {Student (, 19, 22); Student (, 19, 22); Student (, 19, 22 );};

Object Pointer

Pointer to object

Class Box {public: Box (int h = 10, int w = 10, int len = 10 );
Int s; int volume (); private: int height; int width; int length ;}; Box: Box () {height = h; width = w; length = len;} int Box: volume () {return (height * width * length );}
Box * ptr; // pointer to an object
Box t1;
Ptr = & t1;

Pointer to an object Member

1) pointer to the object data member

The general format is as follows:

Data Type name * pointer variable name;

Int * p1; p1 = & t1.s ;//S is public type data

2) pointer to the object member function

Defining pointer variables pointing to object member functions is different from defining pointer variables pointing to common functions. Comparison:

Type name (* pointer variable name) (parameter list); void (* p) (); p = fun; (* p )(); // define the fun function /////////////////////////////////// ////// pointer requirements for object member functions: the type of the pointer variable must match the type of the function on the right of the value assignment number to meet the following three requirements: 1) type and number of function parameters; 2) type of function return value; 3) the class is in the following format: void (Time: * p2) (); the general format is: Data Type name (Class Name: * pointer variable name) (parameter list ); p2 = & Time: get_time; the pointer variable points to a common member function in the form of pointer variable name = & Class Name: member function name
# 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 () {cout 

  This pointer

Each member function contains a special pointer. the pointer name is fixed and is called this pointer.

It is a pointer to an object of this class, and its value is the starting address of the object where the currently called member function is located.

// When calling a. volume, execute (a. height) * (a. width) * (a. length)

Protection of public data

To enable data to be shared within a certain range, and ensure that the data is not modified at will, the related data can be defined as constants.

Regular object

You can add the keyword const when defining an object, and specify the object as a constant object. Constant objects must have initial values, such

Time const t1(23,67,7);

In this way, the values of all data members in object t1 cannot be modified.

Class Name const Object Name (real parameter table) or const class name Object Name (real parameter table)

Tips:

1) if an object is declared as a constant object, you can only call this object.Its common member functionsBut cannot call the common member functions of the object (except the Destructor and constructor ). A common member function is often used to provide a unique external interface of an object.

To reference a data member in a regular object, you only need to declare the member function as const. Void get_time () const;

2) a regular member function can access data members in a regular object, but its value cannot be modified. If the data member is declared as mutable, it can be modified.

The preceding two points ensure that the values of data members in common objects will never change.

  Regular object member (data member and function Member)

Regular data member

Its function and usage are similar to common variables. The key word const is used to declare a common data member. The value cannot be modified;

OnlyParameter initialization table for common dataMembers are initialized. No other function can assign values to members of common data.

Common member functions

If you declare a member function as a common member function, you can only reference the data members in this class, but cannot modify them.

The general form of declaring a common member function:

Type name function name (parameter table) const

Const is a part of the function type. When declaring a function and defining a function, you must have the const keyword. You do not need to add const to the call. A common member function can reference a const data member or a non-const data member.

Do not mistakenly think that the member functions in a common object are always member functions. A common object only ensures that its data member is a member of the common data and its value is not modified. If the const declaration is not added to the member function of a common object, the system compiles it into a non-const member function.

A common member function cannot call another non-const member function.

Constant pointer to object

Declare the pointer variable as the const type, so that the pointer variable remains the initial value and cannot be changed, that is, its orientation remains unchanged.

Time t1 (, 3), t2; Time * const ptr1; ptr1 = & t1; ptr1 = & t2; // error, cannot change the point of ptr1

Class name * const pointer variable name

Pointer variable pointing to a Common Object

Constant variable pointer

Const char * ptr;

The general form of a pointer variable defining a pointer to a constant variable is:

Const type name * pointer variable name;

1) if a variable has been declared as a constant variable, you can only point it with a pointer to the constant variable.

The pointer to a non-const variable cannot be used to point to it. For example

Const char c [] = "boy"; const char * p1; p1 = c; char * p2 = c; // invalid. p2 is not a pointer variable pointing to a constant variable.

2) pointer variables pointing to constant variables can also point to variables that are not declared as const. In this caseYou cannot use this pointer variable to change the value of this variable.For example

Char c1 = 'a'; const char * p; p = & c1;* P = 'B'; // The value of c1 cannot be changed through p.C1 = 'B ';

3) if the form parameter of a function is a pointer to a non-const variable, the real parameter can only be a pointer to a non-const variable, rather than a pointer to a const variable. In this way, you can change the value of the variable to which the pointer variable points during function execution. If the form parameter of a function is a pointer to a const-type variable, obviously the value of the variable pointed to by the pointer variable cannot be changed during function execution. Therefore, the real parameter is allowed to be a pointer to the const variable, or a pointer to a non-const variable. For example

Const char str [] = "boy"; void fun (char * ptr); fun (str); // call the fun function. The real parameter is the address of the const variable and is invalid.

Ing between the form parameter and the real parameter using pointer Variables

Object Reference

Reference similar to a variable

Const Data Summary

Dynamic Object creation and release

The objects defined in the method described above are static. During the program running, the space occupied by objects cannot be released at any time.

Dynamic Object creation: creates an object when the object is used, revokes it when it is not used, and releases the memory space occupied by it.

Such as new Box;

The compilation system opens up a memory space, stores a Box class object in this space, and calls the constructor of this class to initialize the object. However, the user cannot access this object because the object has no object name and the user does not know its address. This type of object becomes an unknown object, but has no name.

After the memory is dynamically allocated using the new operator, a value pointing to the pointer of the new object is returned, that is, the starting address of the allocated memory space. You can obtain this address and access this object through this address. You need to define a pointer variable pointing to the object of this class to store this address.

Box *pt;pt=new Box;

C ++ allows initialization of new objects when pointing to new objects.

Box *pt = new Box(12,13,18);

This statement combines the preceding two statements into one statement and specifies the initial value.

You can use the delete operator to release objects created by new without using them.

delete pt;

When executing the delete operator, the Destructor is automatically called before the memory space is released to complete subsequent cleanup.

Object assignment and assignment

Object assignment

Object Name 1 = Object Name 2

Student stud1,stud2;........stud2=stud1;

1) The value assignment of an object only assigns values to the data member, instead of the member function. The member functions of different objects are the same function code segment and cannot be assigned a value.

2) data members of a category cannot include dynamically allocated data. Otherwise, a value assignment may have serious consequences.

Object Replication

Sometimes multiple identical objects are used, that is, copying objects. Class Name object 2 (Object 1 ). For example:

Box box2 (box1); // use the existing object box1 to clone a new object box2

C ++ also provides a convenient way for users to copy data. Replace the brackets with a copy number.

Box box2=box1;

Class Name Object Name 1 = Object Name 2;

Differences between copying and assigning objects:

An object is assigned a value to an existing object. Therefore, you must first define the object to be assigned a value. Object replication creates a new object from scratch and makes it exactly the same as an existing object.

  Static data members: If you want to share data among multiple objects of the same type, you can use static data members without using global objects.

Class Box {public: int volume (); private: static int height; // static data member int width; int length ;};

If you want the values of data members in each object to be the same, you can define it as a static data member;

Static data members only occupy one space (instead of retaining one space for each object ).

Note:

1) if only the class is declared and the object is not defined, the general data members of the class do not occupy the memory space. Only when the object is defined Can space be allocated to the data members of the object. However, a static data member does not belong to a specific object. the space allocated to the object does not include the space occupied by the static data member. Static data members open up space outside all objects. If a static data member is specified in the class and no object is defined, the static data member can be referenced.

2) static data members are allocated space when the program starts to run and are not released until the program ends.

3) static data members can be initialized, but can only be initialized outside the class.

int Box::height = 10;

The general format is:

Data Type Class Name: static data member name = initial value;

Static is not required during initialization. The parameter initialization table cannot be used to initialize static data members. The default value is 0. The following is an error:

Box (int h, int w, int len): height (h) {}// Error

4) static data members can be referenced by object names or class names.

# Include <iostream> using namespace std; class Box {public: // Box (); Box (int, int); int volume (); // private: static int height; int width; int length ;}; Box: Box (int w, int len) {width = w; length = len;} int Box: volume () {return (height * width * length);} int Box: height = 10; // initialize int mian () {Box box1 () for static data members ), box2 (); // cout <"the box1 is:" <box1.volume () <endl; cout <box1.height <endl; // reference the static data member cout with the object name <box2.height <endl; // Box box2 (, 48); // cout <"the box2 is: "<box2.volume () <endl; cout <Box: height <endl; // reference the static data member cout by class name <box1.volume () <endl; // return 0 ;}

As you can see, if the static data member is public, you can reference the public static data member through the object name outside the class, or you can reference the static data member through the class name. Even if no object is defined, You can reference static data members by class name, indicating that static data members belong to the class but not the object. If it is private, it cannot be directly referenced outside the class. It must be referenced by a common member function.

5) with static data members, data between objects can be communicated to achieve data sharing. Therefore, you do not need to use global variables. Note that the public static data member is different from the global variable. The scope of the static data member is limited to the scope that defines the class.

 Static member functions

The member functions can also be static. Add static before declaring the function in the class.

static int volume();

A static member function is a part of the class rather than an object. To call a public static member function outside the class, use the class name and the domain operator ":".

Box::volume();

In fact, the smaller the value is, the more static member functions are called by the object name. For example, a. volume (); but this does not mean that this function belongs to object a, but only uses the type.

Static member functions are used to process static data members.

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.