Usage of const in C + + class

Source: Internet
Author: User

A summary of the const usage in C + + classes:

Let's look at an example:

Class A

{

Public

A (int x): num (x), b(x) {}

  void Fun (const a& A); const modifier Function Parameters

  int getnum (void) const; const modifier functions that do not modify member variables

void Setnum (int x);

  a& operator= (const a& other); Const modifies the return value and formal parameters of a member function

  Const A operator* (const a& left, const a& right); //const Modifying the return value of a member function

Private

int num; Ordinary Members

const int B; Const member

static int C; Static members

static const int D; Static constant member

};

int A:: c = 0;

const int A:: D = 0;

int A:: Getnum (void) const

{

return num;

}

void A:: setnum (int x)

{

Num +=1;

}

Const A:: operator* (const a& left, const a& right)

{

Return A (Left.num*right.num);

}

One, const member variable

1. Const member initialization: cannot be initialized at the definition, can only be initialized in the constructor list, and must have a constructor

Cause: The const data member is only an interior constant for an object lifetime, and is indeed mutable for the entire class.

Because a class can create multiple objects, different objects can have different values for their const data members.

You cannot initialize a const data member in a class declaration, because the compiler does not know what the value of the Const data member is when the object of the class is not created.

2. Initialization of a const member of static follows the static initialization rule, which is initialized outside the class definition.

To build constants that are constant throughout the class, you should use the enumeration constants in the class, or the static const.

Second, const member functions

1. Parameters for member functions of the const-decorated class

void Fun (const a& A); (1)

void Fun1 (a a); (2)

The second function is inefficient. A temporary object of type A in the function is used for "value passing" parameter a, and the construction, copying, and destruction process of the temporary object will consume time

While the first function improves the efficiency, the use of "reference passing" does not need to produce temporary objects, which saves the time spent in the construction, copying and destruction of temporary objects.

But as long as the reference is likely to change a, so add the const.

Summarize:

(1) The parameter const is usually used when the parameter is a pointer or reference, and can only modify the input parameters to protect its contents from being modified;

If the input parameter is in the "value Pass" mode, since the function will automatically generate a temporary variable for copying the parameter, the parameter does not need to be protected, so it is not cosnt.

(2) For input parameters of non-internal data types, the "value passing" method should be changed to "const reference passing" in order to improve efficiency;

(3) For input parameters of an internal data type, do not change the "value passing" method to "Const reference pass". Otherwise, it will not achieve the purpose of improving efficiency, but also reduce the understanding of functions, such as

void func (int x) should not be changed to: void func (const int& x)

2. member functions of the Const modifier class

int getnum (void) const; (1)

void Setnum (int x); (2)

Some member functions change objects, such as (2), and some member functions do not alter the object, that is, the data members of the object are not modified, such as (1).

To make the meaning of the member function clearer, we can add a const description to the function prototype that does not alter the member function of the object.

(1) Any function that does not need to modify the data member should use the const modifier

In this way, even if you accidentally modify the data members or call a non-const member function, the compiler will also error;

(2) The const member function should increase the const qualification in the function prototype declaration and definition, otherwise the compiler will treat them as different functions

(3) A const object can only call a const member function that is decorated by a const display, and cannot call a non-const member function of the class because it may attempt to modify the data member of a constant

For example:

Const a A (1);

A.getnum (); Right

A.setnum (); Error

However, constructors and destructors have exceptions to this rule, and they are never defined as constant members, but can be called by constant objects.

(4) The role of the const member function

Improve the readability of the program; (const member functions do not modify the values of data members; non-const member functions are modified)

Improve the reliability of the program; (If you modify the value of a data member in a const member function, the compiler handles it by mistake)

(5) When defining a const member function, place the const keyword between the function's parameter table and the function body.

Why not put it before the function declaration? This means that the return value of the function is constant and the meaning is completely different.

3. Const modifies the return value of a member function

Const A operator* (const a& left, const a& right);

This declares the return value, which acts as a protection. Prevent the occurrence of the following:

A (1), B (2), C (3);

(A * b) = C;

Summarize:

(1) The general use of the Const modifier return value for the object itself (non-reference or pointer) is used for the second-order operator overloaded function and the creation of new objects;

However, it is generally not recommended that the return value type of a const modifier function be a case of an object or an object reference.

Cause: If the return value is an object, is const, (const A test = instance of a) or a reference to an object is const (const a& test = a instance)

The return value is a const property, the returned instance can only access the common (protected) data member and the const member function in a, and it is not allowed to be assigned operations, which is rarely used in general cases

(2) If a function return value with a "pointer pass" method is added to the const modifier, then the contents of the function return value (that is, the pointer) cannot be modified, the return value can only be assigned to the const-decorated pointer of the same type.

such as: const char * GetString (void);

Char *str = GetString (); Error

Const char* str = GetString (); Right

(3) The function return value uses "The reference pass" the occasion is not many, generally only appears in the class assignment function Hou, the goal is to realize the chain expression:

a& operator= (const a& Other);

A A, B, C;

A = b =c; Right

(A = b) = C; Error

(4) const a& operator= (const a& A); Is that okay?

(5) Do not easily position the return value type of a function as const

(6) In addition to overloading operators, do not generally set the return value type as a const reference to an object

Reference:

1. http://www.cnblogs.com/BloodAndBone/archive/2011/04/12/2013280.html

2. http://www.cnblogs.com/goodloop/archive/2010/04/13/1711368.html

Usage of const in C + + class

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.