Turn: Know the Explicit keyword in C ++

xiaoxiao2021-03-06  36

Transllicit keywords from VCKBASE know C (Danny Kalev Published on 2004-12-28 11:01:04) The constructor with a single parameter implies a conversion operator in the default, please see the following code:

Class C {Int i; // ... public: c (INT I); // Constructor and Implicit Conversion Operator // AS Well};

Void f () {

C C (0);

C = 5; // Put 5 implicitly converted to C object, and then assign

}

The compiler re-edits the above example code, as follows:

//// "c = 5;" "is converted to the following appearance by the compiler: /

C Temp (5); // Instantiate a temporary object, c = Temp; // use = assignment Temp.c :: ~ c (); // TEMP destructor is activated

In many cases, this conversion is intended and is just right. But sometimes we don't want this automatic conversion, for example:

Class string {int size; char * p; // .. public: string (int SZ); // Do not want to make implicit conversion operation}; Void f () {string s (10);

// The following is a programmer's code; an unexpected conversion:

s = 100; // bad, 100 is converted to a string, and then assigned to s}

In order to avoid such implicit conversions, it should be explicitly declared below to declare the constructor of the single parameter:

Class string {int size; char * p; // .. public: // Do not implicitly convert Explicit String (int SZ); string (const char * s, int size n = 0); // implicit conversion};

Void f () {String S (10);

s = 100; // Now compile error; need to explicit conversion:

S = string (100); // Good; Explicit conversion S = "st"; // Good; allow implicit conversion}

转载请注明原文地址:https://www.9cbs.com/read-75699.html

New Post(0)