During the interview, some interviewers are very concerned about some special keywords in C ++;
Sorted out some keywords that are more informative.
• Explicit
Used to declare constructors. The declared constructor is a display constructor and cannot be used in implicit conversion.
A constructor of a parameter in C ++ or a multi-parameter constructor with default values except the first parameter has two functions: 1. Constructing an object; 2. Default and implicit type conversion operators.
1 class foo
2 {
3 public:
4 explicit foo (int)
5: _ member ()
6 {}
7
8 int _ member;
9 };
10
11 int bar (const foo & f)
12 {
13 return f. _ member;
14}
15
16 bar (1); // failed. explicit prohibits implicit (implicit) conversions from int to foo.
17
18 bar (foo (1); // correct, explicitly calling the explicit constructor.
19
20 bar (static_cast <foo> (1); // correct. Use static_cast to call the explicit constructor.
21
22 bar (foo (1.0); // correct. The explicit call to the explicit constructor automatically converts a parameter from a floating point to an integer.
• Mutable
A member variable declared by mutable can be modified in the member function modified by const.
Mutable cannot be used together with const or static.
1 class foo
2 {
3 public:
4 foo ()
5: _ member (0)
6 {}
7
8 void ExChange (int a) const
9 {
10_member =;
11}
12
13 mutable int _ member;
14}
• Volatile
It is used to declare a variable. variables declared by volatile mean that they may be changed by unknown factors of Some compilers, so the compiler will not perform any optimization operations on them.
This provides stable access to special addresses and is mostly used in embedded programming.
1 void foo ()
2 {
3 // volatile int nData = 1;
4 int nData = 1;
5
6 int nData_ B = nData;
7 printf ("nData = % d \ n", nData_ B );
8
9 // c ++ embedded asm see http://asm.sourceforge.net/articles/linasm.html
10 asm ("movl $2,-4 (% ebp) \ n \ r"); // modify the variable address content
11
12 int nData_a = nData;
13 printf ("nData = % d \ n", nData_a );
14}
15
16 Output Using volatile:
17 nData = 1
18 nData = 2
19
20 output without volatile is:
21 nData = 1
22 nData = 1
From Gordon-Ma