The explict and use of C + + keyword

Source: Internet
Author: User

In C + +, the explicit keyword is used to modify the constructor of a class, the class of a constructor that is decorated, the corresponding implicit type conversion cannot occur, and the type conversion can only be performed in a display way.

Explicit precautions for use:

* The explicit keyword can only be used on a constructor declaration inside a class.

* The explicit keyword is used as a constructor for a single parameter.

* in C + +, the explicit keyword is used to modify the class's constructor, the class of the constructor being decorated, and the corresponding implicit type conversion cannot occur.


In C + +, if a class has a constructor that has only one parameter, C + + allows a special way to declare class variables. In this case, you can directly assign a value directly to a class variable that corresponds to the type of the constructor parameter.
The compiler automatically casts the type at compile time, converting the data corresponding to the constructor parameter type to the object of the class. If the explicit modifier is preceded by a constructor, this automatic conversion is prohibited, in which case even the
The data corresponding to the constructor parameter type is assigned directly to the class variable, and the compiler will give an error.
The following is a specific example to illustrate.
Create a People.cpp file, and then enter the following:
class people
{
Public
int age;  People (int a) {age=a; }
};

void foo (void)
{
People P1 (10); Way One
people* p_p2=new people (10); Way Two
People p3=10; Mode three
}

This C + + program defines a class people that contains a constructor that contains only an integer parameter A that can be used to initialize the age variable when the class is constructed.
Then we defined a function foo, in which we created three 10-year-old "people" in three different ways.
The first is the most general way of declaring a class variable.
The second way is to declare a pointer variable of the People class, and then dynamically create a people instance in the heap and assign the address of the instance to P_P2.
The third way is what we call the special way, why say special? As we all know, C + + is a strong type language, different data types can not be arbitrarily converted,
If you want to perform a type conversion, you must explicitly cast the type, and here, without any explicit conversion, directly assigns an integer data to the class variable P3.

Thus, it can be said that an implicit type conversion is done here, and the compiler automatically converts the data corresponding to the constructor parameter type to the object of that class.
Therefore, the method is the same as the final implementation mode of the three-way compiler after the automatic conversion.

What is the role of the explicit keyword? Its role is to prohibit this feature. As at the beginning of the article, a constructor that is modified with the explicit keyword
There is no automatic conversion at compile time, and an error is made.


Here are a few more examples to deepen the impression:

Example one: implicit type conversion when explicit is not added
Class Circle
{
Public
Circle (Double R): R (r) {}
Circle (int x, int y = 0): x (x), Y (y) {}
Circle (const circle& C): R (C.R), X (c.x), Y (C.Y) {}

Private
Double R;
int X;
int Y;
};

int _tmain (int argc, _tchar* argv[])
{
An implicit type conversion occurs
The compiler will turn it into the following code
TMP = Circle (1.23)
Circle A (TMP);
Tmp.~circle ();
Circle A = 1.23;
Note is of type int, which is called circle (int x, int y = 0)
Although it has 2 parameters, but the latter one has a default value, the implicit conversion can still occur
Circle B = 123;
This calculation implicitly calls the copy constructor
Circle C = A;
return 0;
}

When the explicit keyword is added, it prevents the above implicit type conversion from occurring
Class Circle
{
Public
Explicit Circle (Double R): R (r) {}
explicit Circle (int x, int y = 0): x (x), Y (y) {}
Explicit Circle (const circle& C): R (C.R), X (c.x), Y (C.Y) {}
Private
Double R;
int X;
int Y;
};

int _tmain (int argc, _tchar* argv[])
{
3 sentences will be an error.
Circle A = 1.23;
Circle B = 123;
Circle C = A;

Can only be called in the form of a display
This can be done without adding explicit to the copy constructor
Circle A = Circle (1.23);
Circle B = Circle (123);
Circle C = A;

This is the only way to add explicit to the copy constructor.
Circle A (1.23);
Circle B (123);

Circle C (A);

return 0;
}


Example two:
Class A
{
Public
A (int);
Private
int num;
};

int Test (const a&)//an application function
{
...
}

Test (2); That's right
The process is this: the compiler knows that the value passed is int and the function requires a type, but it also knows that calling A's constructor converts int to an appropriate A,
So there is a successful call above. In other words, the compiler handles this call in a situation similar to the following:
Const A TEMP (2); Generates a temporary a object from 2
Test (temp); Calling functions

If the code is written like this:
Class A
{
Public
explicit A (int);
Private
int num;
};


int Test (const a&)//an application function
{
...
}

Test (2); Failed, an int type variable cannot be constructed into a type variable by implicit type conversion.


Example three:
By default, a constructor with only one parameter also defines an implicit conversion that converts data of that constructor's data type to that class object, as shown here:
Class String
{
String (const char* p); Use C-style string p as the initialization value
...
}

String S1 = "Hello"; OK implicit conversion, equivalent to string S1 = string ("Hello");

But there may be times when you don't need this implicit conversion,
As follows: Class String
{
String (int n); The intent is to pre-allocate n bytes to a string
String (const char* p); Use C-style string p as the initialization value
...
}
The following two kinds of writing are more normal:
String S2 (10); OK allocate 10 bytes of empty string
String s3 = String (10); OK allocate 10 bytes of empty string

The following two kinds of writing are more confused:
String S4 = 10; Compile through, and also allocate 10 bytes of empty string
String s5 = ' a '; Compile through, assign an int (' a ') byte of the empty string S4 and S5 respectively an int and char type,
An implicit conversion to an empty string that allocates several bytes is misleading. To avoid this kind of error, we can declare the transformation displayed using the EXPLICIT keyword:
Class String
{
explicit String (int n); The intent is to pre-allocate n bytes to a string
String (const char* p); Use C-style string p as the initialization value
...
}

Coupled with explicit, the implicit conversion of string (int n) is suppressed,
The following two types of notation are still correct:
String S2 (10); OK allocate 10 bytes of empty string
String s3 = String (10); OK allocate 10 bytes of empty string

The following two types of notation are not allowed:
String S4 = 10; Compilation does not pass, implicit conversions are not allowed
String s5 = ' a '; Compilation does not pass, implicit conversions are not allowed
Therefore, at some point, explicit can effectively prevent errors or misunderstandings caused by implicit conversions of constructors.
====================================================================================================
Explicit only works on constructors to suppress implicit conversions. Such as:
Class A
{
A (int a);
};

int Function (a a);
When function (2) is called, 2 is implicitly converted to type A. This situation is often not the result that programmers want, so to avoid it, you can write:
Class A
{
Explicit a (int a);
};

int Function (a a);
Thus, when the function (2) is called, the compiler gives an error message (unless the function has an overloaded form with an int parameter), which avoids errors without the programmer's knowledge.
Note: Only constructors for one parameter, such as:
1, constructor (typename value);
2, Construcor (TypeName value1,typename value2=defaultvalue,typename value3=defaultvalue,...)),
Because the constructors of two parameters have little to no implicit conversion, the case of ClassType classname = value cannot occur (because this can only be assigned to a value).

The explict and use of C + + keyword

Related Article

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.