|
Const basic functions and usage
1. The qualifier is declared as read-only
Use the following method, type in the front / rear with the keyword const, the variable must be initialized, otherwise compilation errors; This variable can not be reassigned, otherwise compilation errors.
Example:
const int i = 50; // compile correctly
const int j; // compile error
int k = 0;
i = k; // compile error
k = i; // compile correctly 1
2. Pertaining to a function parameter, the parameter is protected so as not to be modified
Usage 1: If the parameter is const A * a, you can not change the content of the function pointer passed, so that the pointer points to protect the content, to note here is that the modification does not change the address stored in the pointer is pointing content, but a pointer is pointing to the address can be changed, specific examples are as follows:
void Test (const int * a)
{
* A = 1; // error, * a can not be assigned
a = new int (10086); // correct, it is a pointer to open up a new space, and make * a = 2
}
int main ()
{
int * a = new int (10000);
Test (a);
return 0;
}1
Usage 2: If the parameter is const A & a, you can not change the function passed in reference object, thereby protecting the property of the original object.
For custom data type, passed by reference faster, if you do not want to change the original value, can be used to protect the const parameter, as the following examples:
void Test (const int & a) // L7 in a protection will not be changed
{
a = 2; // error, a constant can not be assigned to
}
int main ()
{
int a = 3;
Test (a);
return 0;
} In fact, for the built-in data types (such as the above example int type), passed by reference does not make much faster. If you are using a reference to the Senate, the general is to change the parameter value; if you do not change the value of parameter values are passed directly to, do not use the const modifier. For custom data types of the input parameters, in order to increase speed and efficiency, you should use "const + pass by reference" instead passed by value. E.g:
The function void Test (A a) to -> void Test (const A & a)
3. Pertaining to the function return values
When the situation with the return value const modified object itself (unquoted and pointer) is used for two purposes operator overloading function and create new objects: Usage 1
Example:
const Rational operator * (const Rational & lhs, const Rational & rhs)
{
return Rational (lhs.numerator () * rhs.numerator (),
lhs.denominator () * rhs.denominator ());
}
Rational a, b;
Radional c;
(A * b) = c; // Error 1
Usage 2: not recommended to use const modifier function returns the value of an object or situation for the type of an object reference. For the following reasons: If the return value is an object const (const A test = A instance) or a reference to an object is const (const A & test = A instance), the return value has the const attribute, instance can only be accessed a class in public (protected) data members and const member functions, and can not perform the assignment, which is rarely used in general, specific examples are as follows:
class A
{
public:
int y;
A (int y): x (x), y (y) {};
void Sety (int y) {this-> y = y;}
};
const A Test1 (A a)
{
return a;
}
const A & Test2 (A & a)
{
return a;
}
int main ()
{
A a (2);
Test1 (a) .Sety (3); // error because Test1 (a) the return value is const, can not be Sety (3) modify
Test2 (a) .Sety (3); // error because Test1 (a) the return value is const, can not be Sety (3) modify
return 0;
} Usage 3: If you give a "pointer is passed" mode function return value const qualifier, the function returns the value (that is, pointers) content can not be modified, the return value can be assigned to the same type const qualifier pointer. Examples are:
const char * GetString (void) {}
int main ()
{
char * str1 = GetString (); // error
const char * str2 = GetString (); // correct
return 0;
} Usage 4: The function returns the value of the use of small "pass by reference", the only in this way is generally a function of the class assignment, the purpose is to achieve chain expression. Examples are:
class A
{
// The following assignment function's return value const qualifier, the return value of the content can not be modified
A & operate = (const A & other);
}
A a, b, c; // a, b, c of object A
a = b = c; // correct
(A = b) = c; // error, a = b return value allowed to be re-assigned 1
4. After the class member function body function plus the const keyword
After the function body class member function with the keyword const, of the form: void fun () const; function in the process does not modify data members. If at the time of writing const member functions, inadvertently modifying the data members, or by calling the other non-const member functions, the compiler error, which greatly improves the robustness of the program.
If the function is not a member of the class, there is no effect, void fun () const; and void func (); is the same.
5. In another connection file reference constants file
Method: Add keywords before type extern const, it represents the reference is constant, so the constant re not allowed to be assigned, for example as follows:
extern const int i; // correct
extern const int j = 10; // error, the difference between two constants can not be assigned constants and #define .const again
1.const constant data type, data type and there is no macro constants
Macro constants only simple character replacement, no type safety checks, and may cause unexpected errors, such as when the character substitutions:
#define = 10
const long & i = 10;
// Since the compiler optimization, so const long i = 10 i is not allocated memory
// But referenced 10 directly substituted into the future, as a result there are no errors in the code later
// Once you turn off all optimization measures, even const long i = 10 can also cause behind the compilation error.
char h = I; // correct
char h = i; // compiler warnings, the number may be due to truncation error caused assignment 2. Use const avoid unnecessary memory allocation
From the assembly point of view, const define constants just shows the corresponding memory address is not the same as #define given immediate, so constant const defined in only one copy of the program is running, and # define constants defined in a number of copies in memory. Examples are:
#define k "Hello world!"
const char pk [] = "Hello world!";
printf (k); // k assigned to the first memory
printf (pk); // allocate memory for the pk time, it will no longer be assigned
printf (k); // k is assigned a second memory
printf (pk);. use some third-const Notes
1. Modify the modified constant value const
The following example, the variable i is const modifier can be carried out by i casts, the address assigned to a new variable, the new variable to be modified which can be modified to change the original const constant.
const int i = 0;
int * p = (int *) & i;
p = 100;. 2 constructors can not be declared const
3.const initialization data members only in the constructor to initialize the table class
class A
{
public:
const int a;
A (int x): a (x) // correct
{
a = x; // error
}
};1
4. Use const reference or pointer should be used, rather than the general object instance in the parameters
Rational use of const member functions of the three uses (parameters, return values, functions), in general, will not easily return type of the function as const; Further, in addition to the general overloaded operators do not return values type set for the const reference to an object.
5. For use const pointer to a modified case
For the following situations, const variable effect on the front and rear position declarator is the same, this case is not allowed to change the contents of a pointer actions:
int i;
const int * a = & i;
int const * a = & i; 1
However, if the const asterisk on the left, the const is used to modify the pointer points to a variable that is a pointer to the address, the contents of the address immutable; if const asterisk on the right, const pointer is modified itself, that the pointer itself is constant:
int i;
// The following line represents a is a pointer can point to any constant int or int variables
// It is always the goal as it points to a constant int
// Can also be written int const * a
const int * a = & i;
// The following line represents a pointer is a constant,
// Initialization must be fixed point to an int variable
After // no longer point to somewhere else
// Pointer but the content can be changed
int * const a = & i; 6 pointer itself is constant, and the pointer points to the content is not constant, in which case the pointer itself can not make changes to operations, such as the following example a ++ is wrong:
int * const a = & i;
a ++; // error, a pointer itself is constant and can not point to other places 7. When the pointer itself and the pointer is pointing to are constant
In this case it can be written as:
8.const member function returns a reference is const; const int * const a = & i
#include
using namespace std;
class A
{
public:
int x;
void set (int x) {this-> x = x;}
// Const member function returns a reference is const, a
// If the front const A & remove mistakes
// Because the return is a const object, the return type is not const
// Returns do not match the content and type of return
const A & Test1 () const
{
// Error. This is a characteristic const member functions
x = 2;
// Is not limited to * this. Whatever is returned, even if it is a non-const object definitions, the result is the same
return * this;
}
};
int main ()
{
A a, b;
// Correct, although returns a const, but with another non-const to receive
b = a.Test1 ();
// Error, since it is an alias, then the type of alias to be the same type as the original
A & c = a.Test1 ();
// Correct although a.Test1 () in a can not be changed, but there has been a function of the scope of members
a.set (2);
// Correct, b received a.Test1 () returns the contents of the data, but it is not const
b.set (2);
// Error. a.Test1 () is an object that is its return value
// Although no name, but it is a.Test1 () return value
// Value is the value a.Test1 () returns, the type is a.Test1 () Returns the type of
. A.Test1 () set (2);
return 0;
} 9.mutable data members declared as variable data
In the C ++ language, mutable using fewer keys, its role is: If a function is const modified, then it will not modify its member variables, but if a member variable is mutable modified, then you can modify .
mutable can be used to point out, even if the class member functions or variables as const, one of its members can be modified. Conversely, variable data can never be a const member, even if it is a member of a const object.
class A
{
public:
int x;
mutable int y;
A (int a, int b): x (a), y (b) {}
};
int main ()
{
const A a (0, 0); // const object must be initialized
a.x = 1; // error
a.y = 2; // correct, mutable modified so that members can be modified, even if the object is a const
return 0;
} |
|
|
|