Bill learns C + + first quarter: a const explanation

Source: Internet
Author: User

0. Article

intends to be the basic knowledge in the book at the same time the systematic collation, convenient for everyone is also convenient for themselves. Collation of knowledge as far as possible reference to book knowledge, than the online access to the information has a higher credibility.

First, from literal constants and constant variables 1, literal constants

A special identifier or expression in a program that satisfies both:
(1) Not addressable (placed in code area)
(2) value is not variable
So it can be treated as literal constants. They are static array names, enumeration variables, global (static variable) first addresses, #define定义的常量.

Integer literal constants:
(1) Previous plus 0 indicates octal
(2) The front plus 0x indicates hexadecimal
(3) Post plus L (recommended) or L, indicates long type
(4) Add U (or u) to indicate unsigned number

Eg.1024ul

2, constant variable const

Allocated space, as with other variables, can be addressed.

Const is defined at the semantic level of the high-level language, and is guaranteed by the compiler to do syntax detection at compile time, but at run time, the const variable is not in read-only memory but is placed in the data area just like a generic variable, so it can be modified as well.

So: The constant variable is a variable with a special restriction, which is understood as a "read-only" variable

Even a const modifier can be modified.

#include <iostream>using namespace STD;voidShowvalue (Const int&i) {cout<<i<<endl;}intMain () {Const intj=5;void*p= (void*) &j;int*ptr= (int*) p; (*ptr) + +;//cout<<j<<endl;//will still display 5, because the compiler optimizes when J is replaced with literal constants 5    //But if it is int i=5; const int j=i; cannot be replaced, direct output J is 6Showvalue (j);//Show 6    return 0; }
3. Constant variable substitution

If the constant variable has an initialization assignment, the compiler replaces the constant variable with the literal constant in the other place.
However, if the start is not initialized it will be wrong

Such as:

void DefineArray(constint n){     int//error,数组大小在编译期确定}int main(){     constint m=5;     int//ok}
4. Literal constants and constant variable addressing
int &r=5//error,无法寻址文字常量,无法建立引用constint &r=5//ok,在数据区开辟一个值为5的无名整数量,然后将引用r与这个整形两绑定
Second, const usage 1, the position of the const
intconst//指向常量的指针(即常指针,const修饰的是int),指向的对象是const型,不可以修改,但是指针p的指向可以修改int *const//指针常量(const修饰的是int*),指针变量p是const型,它的指向不可修改,但是指向的对象可以修改

Const and data types are combined, "constant type". (As a whole)

When you modify a type, you can either put it in front of it, or you can put it behind it, or define a variable with a constant type declaration or const, which only appears before the variable .

There cannot be other identifiers between Const and the modified type.

The reference itself can be interpreted as a pointer constant

So it doesn't make sense to use const before referencing

intconst//const是多余的,编译器warning后忽略const存在

Const with a double pointer, in this case the const is in different positions, the result is different

#include <iostream>using namespace STD;intMain () {int Const**P1;//is not a pointer constant, pointing to an int count* ("int const*" is a pointer to an integral type constant)    int*Const*P2;//is not a pointer constant, but the variable being referred to is a pointer constant (int *const, which is a pointer constant pointing to an integral type, pointing cannot be modified)    intI=5;intj=6;Const int*ptr1=&i;int*Constptr2=&j;    p1=&ptr1; p2=&ptr2;cout<<**p1<<endl;cout<<**p2<<endl;return 0; }

Output:
5
6

The above P1 and P2 assignment is fastidious, if P1=&PTR2 or P2=PTR1 will compile the error

2. Const modifies a class--constant object and constant function

Const decorated Object –> constant object
Const modifier member function---constant function

Modification of any member variable is not allowed in the constant function

Only the constant function of the object can be called through a constant object

#include <iostream>using namespace STD;classa{intNum Public: A () {num=5;}voidDisp ();voidDisp ()Const;void Set(intn) {num=n;}};voidA::d ISP ()Const{cout<<num<<endl;}voidA::d ISP () {cout<<"Non-const version of Disp ()"<<endl;}intMain () {A A1; A1.Set(3);    A1.disp (); AConstA2; A2.disp ();}

Note above:
(1) If the constant function declaration and definition are separated, you need to add a const, or compile the error

Only non-static member functions of a class can be declared as constant functions

(2) If a class has two member functions, the return value, function name, and argument list are identical, one of which is const, then overloaded . Because the arguments of the constant member function pass in the this pointer is a const class* type, the parameters differ, resulting in a different function signature.

Non-read-only objects (such as A1) call a function (such as disp ()), find a non-const version, and then call the const version if not. In the case of a constant object, only the constant function defined in the class can be called, otherwise the compiler will error.

If a non-const object (such as A1) calls a function and has both a const and a non-const version of the function, we want it to call the const function. You must establish a constant reference to the object, or a constant pointer to the object to achieve the purpose. such as: (const a&) a1.disp (); or (const A *) &a1->disp ();

(3) After a constant object is created, its data members are not allowed in the modification. So it is important to display the constructor to initialize the object .

constant object, all member data members are constants regarded.
A non-static constant member of a class object must be initialized in the constructor, and only with the help of an initialization list.

3. const modifier function parameter + function return value
#include <iostream>using namespace STD;voidDISP1 (Const int&ri) {cout<<ri<<endl;}voidDISP2 (Const inti) {cout<<i<<endl;}Const intDISP3 (Const int& RI) {cout<<ri<<endl;returnRI;}int& DISP4 (int& RI) {cout<<ri<<endl;returnRI;}Const int& DISP5 (int& RI) {cout<<ri<<endl;returnRI;}intMainintargcChar* argv[]) {intn=5;    DISP1 (n);    DISP2 (n);    DISP3 (n); DISP4 (n) =6;//Modify reference return valueDISP5 (n);//DISP5 (n) = 6; it's wrong.}

Note:
(1) const modifier parameter, the main function is to refer to the object or to the object , if only the formal parameters, there is little meaning. For example: void disp2 (const int i), where I is not changed in the function, plus no const has no effect.

In addition, defining a similar function with the const modifier and without the const modifier parameter can cause a redefinition error. For example: The value of any integer expression can be passed to the INT parameter variable, or to the const int parameter variable, so it is not overloaded.

(2) The Const modifier does not make much sense when the return value is a normal data, not a reference. Because the function return value is a non-lvalue, the value cannot be changed. Therefore it is on the const int DISP3 (const int& RI), and the return value is decorated with an egg.

(3) If the return value is a reference, the const modifier prevents modification to the referenced object, DISP5 (n) = 6;

(4) Common misconceptions about Const.

Misunderstanding one: The variable value modified with const must not be changed. Const-Modified variables can be indirectly modified by pointers.

Such as:

constint j=5;void *p=(void *)&j;int *ptr=(int *)p;(*ptr)++;

Misunderstanding two: often quoted or often pointers, can only point to the constant variable, which is a great misunderstanding. A constant reference or constant pointer can only indicate that the referenced object cannot be modified by the reference (or the pointer), as to what nature of the referenced object cannot be determined by the constant reference (constant pointer).

Iii. usage of const_cast 1, function

Const_cast is a C + + operator that removes const or volatile in a conforming type

When it is unwise to use const_cast, it can only be said that there is a design flaw in the program. See the following example for the use of the method:

void constTest(){    int i;    cout<<"please input a integer:";    cin>>i;    constint a=i;    int& r=const_cast<int&>(a);//若写成int& r=a;则发生编译错误    ++r;    cout<<a<<endl;}int main(int argc,char* argv[]){    constTest();    return0;}

Input:
5

Output:
6

Summary:
(1) The syntax form of the const_cast operator is const_cast< type> (expression). Brackets must not be omitted

(2) Const_cast can only remove the const or volatile properties of the target, and cannot perform different types of conversions. You can convert const type* to type* only, or const type & to Type &.
The following conversions are wrong:

cons tint A={1,2,3char* p=const_castchar//不能由const int[]转换为char* 

(3) A variable is defined as a read-only variable (a constant variable), then it is always a constant variable. Cosnt_cast cancels the override limit at the time of the indirect reference, and cannot change the const property of the variable itself. The following is an error:

intconst_castint> (i);

(4) You can also convert a const type* type to a type* type or convert a const type& to a type& type by using a forced type conversion in the traditional C language. But the use of const_cast will be better, because const_cast writing complex (reminding the ape not to easily convert), the conversion ability is weak, the purpose is clear, easy to error, easy to check the bug, and C-style forced type conversion ability is too strong, the risk is greater.

Resources

[1] Chen Gang. Advanced Step-by-step tutorials for C + + [M]. Wuhan: Wuhan University Press, 2008.

Bill learns C + + first quarter: a const explanation

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.