Author: yuxq Posted: 2003-08-20 08:37:03
Static is a very common modifier in C , which is used to control the storage methods and visibility of the variable. Here I will talk about the fact that the STATIC modifier is fully analyzed from the Static modifier.
Two major roles of Static:
First, control storage mode:
Static is introduced to inform the compiler, store the variable in the static storage area of the program and the stack space.
1. Terminal: The variable defined inside the function is executed to its definition at the program, the compiler allocates space on the stack. Let's know that the space allocated on the stack is released at the end of this function. This creates a problem: How can I achieve if I want to save the value of this variable in the function to the next call?
The most easy way to define a global variable, but there are many shortcomings defined as a global variable, the most obvious disadvantage is to destroy the access range of this variable (so that variables defined in this function are not only controlled by this function ).
2, Solution: STATIC is introduced in C , use it to modify the variable, it can indicate that the compiler saves this variable in the static storage area of the program, so that the purpose is achieved, and the access range of this variable constant.
Second, control visibility and connection type:
Static has a role that limits the visible range of the variable in the compilation unit, making it an internal connection, at this time, its antonym is "extern".
STITIEC Summary: Static always makes the variable or object storage form into static storage, the connection mode becomes an internal connection, for local variables (already internal connection), it only changes its storage method; for global variables (already It is static stored), which only changes its connection type.
STATIC member in the class:
I. Reasons and role:
1. You need to interact between individual objects of a class, that is, a data object is required for the entire class rather than an object service.
2. At the same time, it is necessary to do not destroy the encapsulation, that is, this member is required to hide the interior of the class and is not visible to the outside.
The STATIC member of the class satisfies the above requirements because it has the following characteristics: there are independent storage area belongs to the entire class.
Second, pay attention:
1. For static data members, the connector guarantees that it has a single external definition. Static data members are initialized in order by definition, pay attention to static members nested, to ensure that the nested members have been initialized. The order of elimination is the reverse order of initialization.
2, the static member function of the class is an object that belongs to the entire class, so it doesn't have this pointer, which results in only the static data and static member functions of the class.
Const is a type modifier that is common in C , but I found it in my work, many people use it just want to be obvious, so, sometimes it will be used, but in some subtle occasions, it is not so lucky. In fact, most of them are due to this source. Therefore, in this article I will analyze const. Trace your own source, the essence, I hope to understand the const by everyone, according to the relationship of thinking, divided into the following sections.
Why is C introduced Const
C proposals originally introduced (or retained) const key based on what kind of purpose? This is an interesting and beneficial topic that is very helpful for understanding const.
1. Everyone knows that C has a type of strict compilation system, which makes the error of the C program to find a lot in the compilation phase, so that the error rate is greatly reduced, so it has become C with C, there is a prominent advantage aspect. 2. The common preprocessing command #define variablename variableValue can be easily replaced, and this value is replacing at least three advantages:
First, avoid the fuzzy number of significance, making the program language clear, as in the case:
#define user_num_max 107 This avoids the confusion brought directly by using 107.
Second, the adjustment and modification of parameters can be easily performed, as in the case, when the number of people is changed to 201, the change will change here,
The third is to improve the performance efficiency of the program. Since the pre-built translator is used, it is not necessary to assign a storage space for these constants, so the efficiency of the execution is higher.
In view of the above advantages, the use of this predefined instruction can be seen everywhere in the program.
3. Speaking here, everyone may confuse the above 1 point, what is the relationship between 2 points and const?, Good, please go down
It seems:
Although there are many advantages over, it has a more deadly disadvantage, that is, the pre-processing statement is only a simple value replacement, lack of type detection mechanism. Such pre-processing statements cannot enjoy the benefits of C strict type checks, which may become hidden dangers that trigger a series of errors.
4. Ok, the first phase is coming out:
Conclusion: The initial purpose of Const introduction is to replace the precompiled instruction, eliminate its shortcomings, while inheriting its advantages.
Now it has become:
Const Dattype VariablenaMe = variableValue;
Why can const can replace a predefined statement?
What is the big god of CONST, so that it can vibrate a predefined statement?
1. First, with constant values, there is variability, which is the basis of replacing the predefined statement.
2. Second, it is obvious that it can also avoid the fuzzy numbers, which can also be easily adjusted and modified.
3. Third, C compilers typically allocate storage space for ordinary constants, but save them in the symbol table, which makes it a constant during compilation, no operation of the memory and read memory, make it efficiency Also very high, this is also an important foundation for replacing the predefined statement. Here, I have to mention, why is this that it is also the basis of it can replace the predefined statement, because the compiler does not read the stored content, if the compiler is allocated to the storage space, it is not possible Become a constant during compilation.
4. Finally, Const definitions are like a normal variable definition, which will be detected by the compiler to it, eliminating the hidden dangers of the predefined statement.
CONST usage classification details
1. Constation for the two cases of pointers:
INT const * a; file: // a variable, * a is not variable
INT * const a; file: // a is not changeable, * a variable
Analysis: Const is a type of clip-bound type modifier, which is a type modifier on the left side and a type modifier, so INT const is limited * A, which is not limited to A. INT * constly defines A, does not limit * a. 2. Contribution value parameters of Const Limit function:
Void Fun (const Int var);
Analysis: The above-described write method defined parameters cannot be changed in the function body. It is understood that the change in VAR in the function body does not affect the external function. Therefore, this definition is not related to the user's user, only related to the writer of the function.
Conclusion: It is best to limit the internal number of functions, and shield the external calorie to avoid confusion. If you can rewrite as follows:
Void fun (int var) {
Const Int & Valias = var;
VARALIAS ....
.....
}
3. Constitu fair value return value:
Const int fun1 ();
Const myclass fun2 ();
Analysis: The return value of the above-mentioned write method cannot be updated. When the function returns the type of internal (such as FUN1), it is already a value, of course, cannot be assigned, so, at this time constant, it is best to remove, so as not to confuse . When a function returns a custom type (such as FUN2), this type still contains a member of the variable that can be assigned, so it makes sense.
4. Transfer and return address: This situation is most common, and the characteristics of the address variable are identical, and the meaning is used in appropriate use of constity.
5. Const Limit class member function:
Class classname {
PUBLIC:
INT fun () const;
.....
}
Note: The form of such const is a regulation, and it is also not confusing. CONST is used in the declaration of this function, because const has become part of the type information.
Get the ability: You can operate a constant object.
Lost ability: You cannot modify the data member of the class, you can't call other functions that are not consts in the function.
In this article, Const knowledge I have not speaking, because I don't want to turn it into a C textbook. I just want to explain it in detail. I will try to say very detailed, because I hope that I have some ideas in a very relaxed and casual atmosphere. After all, the programming is also relaxed, and a part of the happy life . Sometimes, you will be amazed that the world is so beautiful.
[Posted Reply] [View the original post] [Add to Favorites] [Close]
-------------------------------------------------- ------------------------------
FLW Reply to: 2003-08-20 12:36:53
Revenue is essential.
-------------------------------------------------- ------------------------------
Quanliking Reply to: 2003-08-20 19:37:11
Thank you!
-------------------------------------------------- ------------------------------
Jobman Reply to: 2003-08-21 00:13:43
There are a few different opinions:
[CODE: 1: 3186D5E9BE] Although there are many advantages over, it has a more deadly disadvantage, ie, the pre-processing statement is just a simple value replacement, lack of type detection mechanism. Such pre-processing statements cannot enjoy the benefits of C strict type checks, which may become hidden dangers that trigger a series of errors. [/ Code: 1: 3186d5E9be] Macro definition is done when pre-processed, but still want to pass compiler, it is impossible to escape the type.
Check, for example:
[Code: 1: 3186d5E9be] #define my_macro "fsdfsdfdsdf"
INT FUNC1 (int parameter)
{
.....
}
Main ()
{
FUNC1 (MY_MACRO);
} [/ code: 1: 3186d5e9be]
This code is definitely unable to compile, so this description is not established.
Macro definition skills are also profound, not Const can replace,
Of course, it is good to replace the macro definition in the case of the value.
Choose, but only this is only, and the macro definition does not introduce type hidden dangers.
The introduction of Const is not in replacing macro definitions, which is a bit stiff.
-------------------------------------------------- ------------------------------
Xiaofei loves Shenhua Reply to: 2003-08-21 03:23:02
[quote: fb2fd29f5e = "quanliking"] Thank you! [/ quote: FB2FD29F5E]
The vest is wrong, ^ _ ^
-------------------------------------------------- ------------------------------
CLION Reply to: 2003-08-21 20:46:49
This post is very good.
-------------------------------------------------- ------------------------------
Aero Reply to: 2003-08-21 21:00:31
[quote: E4afadc072 = "jobman"]
This code is definitely unable to compile, so this description is not established.
Macro definition skills are also profound, not Const can replace,
Of course, it is good to replace the macro definition in the case of the value.
Choose, but only this, and use macro definitions will not .......... [/ quote: E4afadc072]
Oh, the two are right. However, the compiler checks the type of inspection that occurs in Int func1 (int parameter), not in #define my_macro "fsdfsdfdsdf"
. So the original text is still true, Jobman's meaning is also right.
-------------------------------------------------- ------------------------------
Happywin Reply to: 2003-08-24 16:46:11
Essence, collection
-------------------------------------------------- ------------------------------
Heaven's little stars Reply to: 2004-02-10 11:44:07
Good sticker
-------------------------------------------------- ----------------------------- Whyglinux Reply to: 2004-04-10 03:51:16
[quote: EDC740AFB5 = "yuxq"] ...
5. Const Limit class member function:
Class classname {
PUBLIC:
INT fun () const;
.....
}
Note: The form of such const is a regulation, and it is also not confusing. CONST is used in the declaration of this function, because const has become part of the type information.
Get the ability: You can operate a constant object.
Lost ability: You cannot modify the data member of the class, you can't call other functions that are not consts in the function.
[/ quote: EDC740AFB5]
This article of the landlord is worth reading. However, I think the part of the above "Const Limit Class" is written relatively simple, especially the text behind "Note", which makes people unclear clouds, so I want to make some additional instructions for this part.
After the member function of the class, CONST is added, indicating that this function does not change any changes to the data member of this class object (accurately non-static data member). When designing a class, a principle is to add const on the membership function that does not change the data member, and the member function that changes the data member cannot be added to CONST. Therefore, the CONST keyword has a more clear qualification for the behavior of the member function: a member function with const modified (referring to the const behind the function parameter table, not in front of the function or within the parameter table), can only read data members You cannot change the data member; there is no Const modified member function, which is readable to the data member. In addition, what is the benefit of add const on the member function of the class? The landlord told us: "Get the ability: Operating constant object", actually should be a constant (ie const) object to call the Const member function without calling non-const modified functions. As non-const type data can be assigned to the const type variable, it is not true.
Please see a complete example below, then I will make some instructions.
[Code: 1: EDC740AFB5]
#include
#include
Using namespace std;
Class student {
PUBLIC:
Student () {}
Student (const string & nm, int sc = 0)
: Name (nm), score (sc) {}
Void set_student (const string & nm, int sc = 0)
{
Name = nm;
Score = sc;
}
Const string & get_name () const
{
Return Name;
}
INT GET_SCORE () Const
{
Return score;
}
Private:
String name;
int score;
}
// Output Student's Name and Score
Void Output_student (Const Student & Student)
{
COUT << student.get_name () << "/ t";
COUT << student.get_score () << endl;}
int main ()
{
Student Stu ("WANG", 85);
Output_student (STU);
}
[/ Code: 1: EDC740AFB5]
A class Student is designed, and the data member has Name and Score, there are two constructor, with a setup member data function set_student (), each has a function GET_NAME () and get_score (). Note that get_name () and get_score () have added const, and set_student () is not (no const).
First of all, there is a list of external words, why Get_name () is also added in front. If there is no two constings before and after, get_name () returns a reference to the private data member name, so you can change the value of the private member name by this reference, such as
[CODE: 1: EDC740AFB5] Student Stu ("WANG", 85);
Stu.get_name () = "li";
[/ Code: 1: EDC740AFB5]
That is, the NAME is turned from the original "wang" into "li", and this is not what we hope. So before get_name (), add CONST to avoid this happening.
So, get_name () and get_score () should be added to the Const's member function, can you not be a constraint? Answer is available! But the price of this is: Const object will no longer call these two non-Const member functions. Such as
[CODE: 1: EDC740AFB5] const string & get_name (); // These two functions should be set to a ConST type
INT get_score ();
Void Output_student (Const Student & Student)
{
COUT << Student.get_name () << "/ t"; // If get_name () and get_score () are non-Const member functions, this sentence and the next call is wrong
Cout << student.get_score () << Endl;
}
[/ Code: 1: EDC740AFB5]
Since the parameter student represents a reference to the Const Student type object, Student cannot call non-Const member functions such as set_student (). If the get_name () and get_score () member functions become non-Const type, the use of STUDENT.GET_NAME () and student.get_score () is illegal, so it will have difficulty handling us.
Therefore, we have no reason to object to use const. When you add const, we should add const, which enables member functions, in addition to non-Const's object, the Const object can call it.
http://lhb7788.yculblog.com/post-172815.html