Another built-in type bool exclusive to C ++. It is only a special case, because we do not need operators like ++ for boolean values. On the contrary, we need specific boolean operators such as & = and | =. Therefore, this type is defined separately:
Class bool {public: bool (bool x = false): Data _ (x) {} operator bool () const {return data _;} bool & operator = (bool X) {data _ = x; return * This;} bool & operator & = (bool X) {data _ & = x; return * This ;} bool & operator | = (bool X) {data _ | = x; return * This;} PRIVATE: bool data _ ;}; inline STD :: ostream & operator <(STD: ostream & OS, bool B) {If (B) OS <"true"; elseos <"false"; return OS ;}
Similarly, like other built-in classes, the behavior of the bool type is exactly the same as that of the bool type (the original built-in type). The only difference is that:
- It is initialized to false.
- It has the <operator to print false and true, instead of 0 and 1, which is clearer and easier to understand.
But why is it initialized to false instead of true? In fact, they are all the same. We can also write a new class and initialize it to true by default.
So far, the motive for using a class such as int, unsigned, and double to replace the built-in types of lowercase letters is to avoid initializing them in multiple constructors. If you use them more broadly, for example, to pass the parameters to the function, the result will be like this. Suppose there is a parameter function that accepts the unsigned type (built-in type:
Void somefunctiontaking_unsigned (unsigned U );
The following code can be compiled:
Int I = 0; somefunctiontaking_unsigned (I );
This is not the case if we use the class we are discussing. For such a function:
Void somefunctiontakingunsigned (unsigned U );
The following code cannot be compiled:
Int I = 0; somefunctiontakingunsigned (I );
Therefore, in this case, we automatically obtain the advantages of type security during compilation.
Summary:
- Do not use built-in types such as int, unsigned ·, double, and bool as data members of the class. Instead, use int, unsigned, double, bool, and other classes, because this avoids initialization of them in the constructor,
- Replace the built-in types with these new classes to represent the parameters passed to the function for extra type security.
Uninitialized Boolean value (2)