[Reproduced] Const usage

xiaoxiao2021-03-06  43

The usage of Const keywords in C is very flexible, and use const will greatly improve the robustness of the program, refer to the use of the Const use of Kang Jian Dong brother, some additions to it, wrote this article.

1. Const constant, such as const Int max = 100;

Advantages: The constant has a data type, while the macro regular amount has no data type. The compiler can perform type security checks for the former, and only characterize only characters, there is no type of security check, and the unexpected error may occur when character replacement (marginal effect)

2. Data members of Const modifiers. Such as:

Class A

{

CONST INT Size;

...

}

Const data members are constants only in an object survival, and they are variable for the entire class. Because classes can create multiple objects, different objects of different objects can be different. So you can't initialize the Const data member in the class declaration, because the compiler does not know what the value of the Const data member is not found. Such as

Class A

{

const Int size = 100; // Error

INT Array [size]; // error, unknown SIZE

}

Initialization of Const data members can only be performed in the initialization table of the constructor of the class. To build constant constant in the entire class, you should implement the enumeration constant in the class. Such as

Class A

{...

ENUM {size1 = 100, size2 = 200};

Int Array1 [Size1];

Int array2 [size2];

}

The enumeration often does not take up the storage space of the object, and they are fully evaluated when compiling. However, the implicit data type of the enumeration is an integer, its maximum value is limited, and cannot represent floating point numbers.

3. The case of const modifying pointers, see the following formula:

INT b = 500;

Const Int * a = & [1]

INT const * a = & [2]

INT * const a = & [3]

Const Int * Const a = & [4]

If you can distinguish these four situations, then, congratulations, you have taken a welcome step. I don't know, it doesn't matter, we can refer to the practice of "Effective C " Item 21, if constant is on the left side of an asterisk, then const is the variable pointed to the pointer, that is, the pointer points to constants; if const is in an asterisk On the right side, Const is the modified pointer itself, that is, the pointer itself is constant. Thus, [1] and [2] are the same, all of which are pointed to by the pointer (constant is not related to the location of the variable declaration), and the content is not allowed to change the operation, if not * a = 3; [3] The pointer itself is constant, and the content points to the pointer is not constant. In this case, the pointer cannot be changed, such as a is wrong; [4] is the pointer itself and the pointing content For constant.

4. Initialization of Const

Let's take a look at the situation of Const variable initialization

1) Cases of non-pointer constant constant: a b;

Const a a = b;

2) What is initialized by the pointer constant constant:

A * D = new a ();

Const a * c = d;

Or: const a * c = new a (); 3) Reference CONST constant initialization:

A f;

Const A & E = f; // This can only access a function of declaring Const, and cannot access one

Phetican function;

[Thinking 1]: Is this assignment method correct?

Const a * c = new a ();

A * E = C;

[Reflection 2]: Is this assignment method correct?

A * const c = new a ();

A * b = C;

5. Some of the powerful features of Const lies in its application in the function declaration. In a function declaration, const can modify the return value of the function, or a parameter; for a member function, it is also modified to be a whole function. There are several situations that will gradually explain: A & Operator = (Const A & a);

Void Fun0 (Const A * a);

Void fun1 () const; // fun1 () for class member functions

CONST A FUN2 ();

1) Const, such as Void Fun0 (Const A & A); Void Fun1;

When the function is called, the constant constant is initialized with the corresponding variable, and in the function body, constant quantization is performed according to the part modified by const, such as constit a * a, and cannot change the content of the passed pointer, Protect the content points to the original pointer; if the shape is referred to Const A & A, it cannot be changed to the transferred reference object, and the properties of the original object are protected.

[Note]: Parameter const is usually used for the case where the parameter is a pointer or reference, and can only modify the input parameters; if the input parameter is "value passed" mode, since the function will automatically generate temporary variables to copy this parameter, this parameter It doesn't matter if you need it, so you don't have to modify.

[Summary] For input parameters of non-internal data types, the purpose is to improve efficiency because it is changed to "Const References" in the way. For example, change Void Func (a a) to Void Func (Const A & A)

For input parameters for internal data types, do not change the "value to" to "Const reference". Otherwise, it will not only improve the efficiency, and the understandability of the function is reduced. For example, Void func (int X) should not be changed to Void Func (Const Int & X)

2) Const a fun2 (); const a * fun3 (); const A * fun3 ();

This declares that the return is modified according to the "Modification Principles" and plays a corresponding protection. Const Rational Operator * (Const Rational & lh, Const Rational & RHS)

{

Return Rational (LHS.NUMERATOR () * rhs.Numerator (),

LHS. Denominator () * rhs.denominator ());

}

Return Value Use const modifiers to prevent such operations from occurring: Rational A, B;

Radional C;

(a * b) = C;

Generally, the case where the CONST modified return value is the object itself (non-reference and pointer) is used for the bull operator overload function and generates a new object.

[to sum up]

1. In general, when the return value of the function is an object, if it is declared as const, it is used to overload the operator. Typically, it is not recommended to use the const modified return value type as an object or a case referenced to an object. The reasons are as follows: If the return value is a reference for a const (const A test = a instance), or a reference to a reference is const (const A & test = a instance), the return value has a const attribute, then the return instance can only be accessed The public (protected) data member and the Const member function in class A, and does not allow assignment operations, which are rarely used in general. 2. If a function returns a value to a "pointer delivery" method, the content returns (ie, the pointer) can not be modified, the return value can only be assigned to the same type of CONST modified. Such as:

Const char * getString (void);

The following statement will appear compilation:

CHAR * STR = getString ();

The correct usage is:

Const char * str = getString ();

3. Function return value is not much in the case of "reference delivery", which typically only appears in the 赙 value function of the class, and the purpose is to achieve chain expression. Such as:

Class A

{...

A & Operate = (const a & other); / / negative function

}

Objects A A, B, C; // A, B, C is A

...

A = b = c; // Normal

(a = b) = C; // is not normal, but legal

If the return value of the negative value is plus const modification, the content of the return value is not allowed to modify, and the A = B = c is still correct in the above example. (a = b) = c is incorrect.

[Think 3]: Is this defined assignment operator overload function?

Const A & Operator = (Const A & A);

6. Use of Const in the class member function

After the function is generally placed, the shape is like: void fun () const;

Any function that does not modify the data member is due to the statement as a const type. If you write a Const member function, you accidentally modify the data member, or call other non-Const member functions, the compiler will report an error, which greatly enhances the robustness of the program. Such as:

Class Stack

{

PUBLIC:

Void Push; INT ELEM

INT POP (Void);

INT getCount (void) const; // constist member function

Private:

INT m_num;

INT M_DATA [100];

}

INT Stack :: getCount (void) Const

{

m_num; // Compiling errors, attempt to modify data members m_num

POP (); // Compiling errors, trying to call non-Const functions

Return m_num;

}

7. Some suggestions using const

1 To use Const bold, this will bring you endless benefits, but the premise is that you have to figure out the original committee;

2 To avoid the most general assignment operations, if you assign the Const variable, you can see the questions;

3 Use const in parameters to use references or pointers, not general object instances, the reason is the same.

4 The three usage (parameters, return values, functions) in the member function (parameters, return values, functions) should be used well; 5 Do not easily set the function's return value type as const;

6 Do not specify the return value type as a const reference to an object except for overloaded operators;

[Thinking question answer]

1 This method is incorrect because the purpose of the declaration pointer is to change the content points to it, and the declared pointer e points to a constant, so it is incorrect;

2 This method is correct because the content points to which the pointer points to;

3 This approach is incorrect;

In Const A :: Operator = (Const A & A), the use of Const in the parameter list is correct, and when this continuous assignment, the problem will appear:

A a, b, c:

(a = b) = C;

Because the return value of a.Operator = (b) is a const reference to A, the CONST constant cannot be assigned again.

转载请注明原文地址:https://www.9cbs.com/read-59065.html

New Post(0)