(译)What does explicit keyword mean?

The answer is taken from the original Overflow Stack: the What does Explicit keyword at The Mean?

When the parameters passed to the function, if the variables do not match, C ++ compiler that is done once implicit type conversion as much as possible to meet the requirements of the parameters of the function. Implicit type conversion will involve single argument constructor call conversion target, the following is an example of an implicit conversion:

1
2
3
4
5
6
7
8
9
10
11
12
13
class 
{
public:

Foo (int foo) : m_foo (foo)
{
}

int GetFoo () { return m_foo; }

private:
int m_foo;
};

A function with the Fooobject as a parameter:

1
2
3
4
大专栏  (译)What does explicit keyword mean?lass="line">void DoBar (Foo foo)
{
int i = foo.GetFoo ();
}

Now we call the following DoBarfunction:

1
2
3
4
int main ()
{
Solid ( 42 );
}

Obviously, the type of argument is not Foo, but int, but in Foothe object constructor which has a single parameter of type int to accept a constructed object, so the compiler will implicitly call this constructor to intconvert a Foo.

This constructor to specify the display is explicitthat tells the compiler that we do not want this type of implicit conversion, the compiler will prohibit such conversion, if we use it again DoBar(42)it will error.

The reason for making this keyword reason is because of this implicit conversion compiler may give our program to bring some subtle bug. For example: There are a constructor for a class: MyString(int size)indicates the length of this character initialization 3. You call this function print(const MyString&)want to print this character, but sloppy code that you wrote print(3). You want it is to print out the character "3", but the actual returns an empty string and a length of 3.

Programming recommendation: generally required for single-argument constructor (including multi-parameter constructor with default parameters) plus explicit.

Guess you like

Origin www.cnblogs.com/sanxiandoupi/p/11693064.html