2.17 C + + class and const keyword

Source: Internet
Author: User

Reference: http://www.weixueyuan.net/view/6348.html

Summarize:

 The initialization of const member variables has only one path: the parameter initialization table.

The const member function can use all member variables in the class, but cannot modify the value of the variable.

The normal member function cannot access the member variables of the constant object, the other member variables can be accessed, the normal member function can modify the member variable is also only non-const member variables.

Once an object is defined as a constant object, the object can only invoke the regular member function in the class.

Requires modifying a member variable in a constant object, which cannot be modified if it is a normal member variable.  To meet this requirement, C + + provides the mutable keyword. Constant object calls the const member function to modify the variable.

Sometimes in order to avoid any modifications to the object itself in the function, precede the function parameter with the const keyword.

In a class, some data that people do not want to be modified is sometimes modified to avoid mis-operation and must be qualified with the Const keyword. The Const keyword allows you to define member variables, member functions, constant objects, and common references to objects of the const type.

Const member Variable

The const member variable uses a similar usage to the normal const variable usage, which you can simply precede with the const keyword. the initialization of the C ONST member variable has only one path: the parameter initialization table. this has been mentioned earlier, do not remember the words can be looked at the parameters of the initialization table that section.

Const member functions

The const member function can use all member variables in the class, but cannot modify the value of the variable , which is set primarily to protect the data.

Let's take a look at the following example, Example 1 is still the book class that has been seen many times before, but the code that is not related to the Const member function has been removed. Two constructors and four normal member functions are defined in the class, with the functions of setting member variables and getting member variables. But this book class is not the same as before the GetPrice function and the GetTitle function declaration after the Const keyword, which is the const member function, you can also become a regular member function. The constant member function is to add the Const keyword at the end of the function's head when declaring and defining it. Note that the Const keyword is still not very small when defining a function, see the definitions of GetPrice and GetTitle functions in Example 1.

Why would you define these two functions as regular member functions? The function of these two functions we know is to return the price and title, the function of a single, and do not want to modify these two variables, so, it is very safe to define the regular member function, you can avoid the two functions to modify the member variable. If you need to modify these two variables simply by Setprice and the Settitle function, it is very appropriate to set to Const.

Example 1:

  1. Class Book
  2. {
  3. Public:
  4. book(){}
  5. book(Char* A, double p = 5.0);
  6. void setprice(double A);
  7. void settitle(Char* a);
  8. Double GetPrice()const;
  9. Char * gettitle()const;
  10. Private:
  11. double price;
  12. Char * title;
  13. };
  14. Double book::getprice()const
  15. {
  16. return price;
  17. }
  18. Char * Book::gettitle()const
  19. {
  20. return title;
  21. }

The constant member function can access any member variable in the class, but cannot modify any member variable. while the normal member function cannot access the member variables of the constant object, other member variables can be accessed, the ordinary member function can modify the member variables are also only non-const member variables, once the const keyword is added to decorate, initialization can not be modified after the completion of the. It is also important to note that the Const member function cannot call the non-const member function of the class.

Const Object

The basic syntax for the Const object definition is as follows:
Const Class Name Object name (argument name);
Class Name Const object Name (argument name);
Both of these definitions are possible, and once the object is defined as a constant object, the object can only invoke the regular member function in the class.

Example 2:

#include <iostream>using namespacestd;classbook{ Public: Book () {} Book&b); Book (CharBDoublep =5.0); voidSetprice (Doublea); DoubleGetPrice ()Const; voidSettitle (Char*a); Char* GetTitle ()Const; voidDisplay ()Const;Private:    DoublePrice ; Char*title;}; Book::book ( Book&b) { Price=B.price; Title=B.title;} Book::book (CharADoublep) {Title=A; Price=p;}voidBook::d isplay ()Const{cout<<" The price of"<<title<<"Is $"<<price<<Endl;}voidBook::setprice (Doublea) { Price=A;}DoubleBook::getprice ()Const{    returnPrice ;}voidBook::settitle (Char*a) {Title=A;}Char* Book::gettitle ()Const{    returntitle;}intMain () {ConstBook Alice ("Alice in Wonderland",29.9);    Alice.display (); Alice.setprice (51.0);//Compile Error    return 0;}

In this example, we declare the GetPrice, GetTitle, and display three functions in the class as constant member functions, and then in the main function we define a constant object Alice,alice as a constant object, and only the constant member function can be called. Therefore, there is no problem when calling the display function, but compiling an error when calling the Setprice function, because Setprice is not a regular member function.

Sometimes we need to modify a member variable in a regular object during the process of programming , if it is a normal member variable, it cannot be modified. To meet this requirement, C + + provides the mutable keyword.

    1. mutable int var;

The variable var is declared as a variable member variable by such a declaration, and if you want to modify the variable for a constant object, you only need to modify the variable by calling the Const member function from the regular object.

Const reference to Object

When we use an object as a function parameter, we usually use reference as a function parameter. Sometimes in order to avoid any modifications to the object itself in the function, precede the function parameter with the const keyword.

Example 3:

#include <iostream>using namespacestd;classbook{ Public: Book () {} Book&b); Book (CharBDoublep =5.0); voidSetprice (Doublea); DoubleGetPrice ()Const; voidSettitle (Char*a); Char* GetTitle ()Const;Private:    DoublePrice ; Char*title;}; Book::book ( Book&b) { Price=B.price; Title=B.title;} Book::book (CharADoublep) {title=A; Price=p;}voidBook::setprice (Doublea) { Price=A;}DoubleBook::getprice ()Const{    returnPrice ;}voidBook::settitle (Char*a) {Title=A;}Char* Book::gettitle ()Const{    returntitle;}voidDisplayConstBook &b) {B.setprice (59.9);//Compile Errorcout<<" The price of"<<b.gettitle () <<"Is $"<<b.getprice () <<endl;//OK}intMain () {Book Alice ("Alice in Wonderland",29.9);    Display (Alice); Book Harry ("Harry Potter",49.9);    Display (Harry); return 0;}

In this example, we declare the display function as a top-level function whose function parameter is a constant reference to the book class object, and in the function we first call the public property's Setprice function, attempting to modify the price member variable, and the compilation fails. It is not a problem to call the GetTitle and GetPrice functions later, because these functions do not modify member variables.

2.17 C + + class and const keyword

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.