C ++ learning const member variables and member functions

Source: Internet
Author: User

A common type is a type described by the Type modifier Const. The values of variables or objects of a common type cannot be updated. Therefore, Initialization is required to define or describe the common type.

If a class declares a regular data member, no function can assign a value to this member. The constructor initializes the member only through the initialization list.

# Include <iostream>
Using namespace STD;
Class
{
Public:
A (int I );
Void print ();
Const Int & R; // constant reference
Int C;
PRIVATE:
Const int;
Static const int B; // static data member
 
};
Const int A: B = 10; // static constant data members are initialized out of class
A: A (int I): A (I), R (c)
{
 
}
Void A: Print ()
{
Cout <A <":" <B <":" <r <Endl;
}
Int main ()
{
A A1 (100), A2 (0 );
A1.print ();
A2.print ();
// A1.r = 30; error because R is a constant reference. The target value cannot be changed by reference.

// The reference declared in this way cannot be modified by reference to the value of the target variable, so that the referenced target becomes const, achieving the security of reference.
Return 0;
}

A reference is an alias of a variable (target). The referenced operation is exactly the same as the direct operation on a variable. The declared method of reference: type identifier & reference name = target variable name; Description: (1) & this is not an address calculation, but an identifier.

(2) type identifier refers to the type of the target variable.

(3) When declaring a reference, it must be initialized at the same time.

(4) After the reference declaration is complete, it is equivalent that the target variable name has two names, namely, the original name and reference name of the target, and the reference name cannot be used as the alias of other variable names.

Int A, & RA =;

A is the original name of the target, and Ra is the reference name of the target. Assign a value to RA: rA = 1; equivalent to a = 1;

(5) declaring a reference is not a new variable. It only indicates that the reference name is an alias of the target variable name. It is not a data type, therefore, the reference itself does not occupy storage units, and the system does not allocate storage units to the reference. Therefore, finding the address for the reference is to find the address for the target variable. & RA and &.

(6) arrays cannot be referenced. An array is a collection composed of several elements, so an array alias cannot be created.

Example: Point pt1 (10, 10 );

Point & pt2 = pt1; defines a reference where pt2 is pt1. With this definition, pt1 and pt2 indicate the same object.

It is important to note that references do not generate copies of objects, but are only synonyms of objects. Therefore, after the current statement is executed:

Pt1.offset (2, 2 );

Both pt1 and pt2 have (12, 12) values.

The reference must be initialized immediately during definition because it must be a synonym for something. You cannot define a reference before

Initialize it. For example, the following statement is invalid:

Point & pt3;

Pt3 = pt1;

So what is the purpose of referencing a synonym for something?

The following two main purposes of reference are discussed: as a function parameter and return the left value from the function.

Ii. reference parameter 1. Passing variable parameters

In traditional C, parameters are passed through values when a function is called, which means that the function parameters do not have the ability to return values.

Therefore, in traditional C, if function parameters are required to have the ability to return values, they are usually implemented through pointers. For example

The C program for the exchange of two integer values is as follows:

Void swapint (int * a, int * B)

{

Int temp;

Temp = *;

* A = * B;

* B = temp;

}

After the reference mechanism is used, the C ++ version of the above program is:

Void swapint (Int & A, Int & B)

{

Int temp;

Temp =;

A = B;

B = temp;

}

The C ++ method that calls this function is: swapint (x, y); C ++ automatically transmits the address of X and Y to the swapint function as a parameter.

2. Passing large objects to Functions

When a large object is passed to a function, the parameter transfer efficiency can be improved by using reference parameters, because reference does not produce

Copy, that is, when the parameter is passed, the object does not need to be copied. The following example defines a class with a finite Integer Set:

Const maxcard = 100;

Class Set

{

Int elems [maxcard]; // The element in the set. maxcard indicates the maximum number of elements in the set.

Int card; // The number of elements in the set.

Public:

Set () {card = 0;} // Constructor

Friend set operator * (set, set); // reload operator number *, used to calculate the intersection of a set, using an object as a value passing Parameter

// Friend set operator * (set &, set &) overload operator number *, used to calculate the intersection of sets and use the object reference as the value passing Parameter

...

}

First consider the implementation of set intersection

Set operator * (set set1, set set2)

{

Set res;

For (INT I = 0; I <set1.card; ++ I)

For (Int J = 0; j> set2.card; ++ J)

If (set1.elems = set2.elems [J])

{

Res. elems [res. Card ++] = set1.elems;

Break;

}

Return res;

}

Since the overload operator cannot operate the pointer independently, we must declare the number of operations as the set type rather than set *.

When * is used for intersection operations, the entire set is copied, which is very inefficient. We can use references to avoid this situation.

Set operator * (set & set1, set & set2)

{Set res;

For (INT I = 0; I <set1.card; ++ I)

For (Int J = 0; j> set2.card; ++ J)

If (set1.elems = set2.elems [J])

{

Res. elems [res. Card ++] = set1.elems;

Break;

}

Return res;

}

Edit this section 3. Reference return values

If a function returns a reference, the function call can also be assigned a value. Here is a function that has two reference parameters and returns a double-precision reference:

Double & MAX (double & D1, double & D2)

{

Return D1> D2? D1: D2;

}

Because the max () function returns a reference to the Double Precision number, we can use max () to add 1 to the large double precision number:

Max (x, y) + = 1.0;

Edit this section 4. Regular reference

Common Reference declaration method: const type identifier & reference name = target variable name;

The reference declared in this way cannot be modified by reference to the value of the target variable, so that the referenced target becomes const, achieving the security of reference.

[Example ]:

Int;

Const Int & RA =;

Ra = 1; // Error

A = 1; // correct

This is not just to make the code more robust, but also some other needs.

[Example]: Assume the following function declaration is available:

String Foo ();

Void bar (string & S );

The following expression is invalid:

Bar (FOO ());

Bar ("Hello World ");

The reason is that both the Foo () and "Hello World" strings generate a temporary object. In C ++, these temporary objects are of the const type. Therefore, the above expression tries to convert a const type object to a non-const type, which is invalid.

The referenced parameter should be defined as const if it can be defined as Const.

Edit section 5. References and Polymorphism

References are another method that can produce polymorphism effects except pointers. This means that a base class reference can point to its derived class instance.

[Example ]:

Class;

Class B: Public {......};

B;

A & ref = B; // use a derived class object to initialize a reference to a base class Object

Ref can only be used to access the members inherited from the base class in a derived class object. It is a base class reference pointing to a derived class. If a virtual function is defined in Class A, and this virtual function is rewritten in Class B, a multi-state effect can be generated through ref.

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.