C ++ does not have explicit, implicit conversion between the class hierarchy 2013-07-11 15:41

Long time no write blog, and today see the implicit and explicit conversion of a chapter talking about the class at the time of learning c #. Hereby left pen, for later reference.

        About the explicit, implicit conversions Some argue that what is not recommended implicit conversion. But personally I believe that non-essential, if there is a good foundation for writing basis, then the implicit and explicit conversion is no difference, but rather an implicit conversion more convenient.

        Said first explicit conversion now CPoint classes and class CRect; CRect object to cast objects CPoint type.

The idea is to achieve: CPoint overloaded constructor, overloading both parameters CRect type of structure parameters can be, this time explicit optional, but recommended that individuals have explicit keywords, any transfer must be strong. This can develop good writing specifications. The CPoint obj = (CRect) rect; ratio CPoint obj = rect better readability. If there is no explicit keywords, it belongs to the implicit conversion.

Pseudocode: explicit CPoint (const CRect & obj) This is a strong explicit transfer; CPoint (const CRect & obj) is a kind of implicit conversion. The first personal favorite way of writing

The CRect object into an object CPoint implicit type.

(1) CPoint constructor overload, CRect parameter type, but without explicit modification constructor.

(2) Overload CPoint assignment function, both heavy =. Pseudocode: CPoint & operator = (const CRect & obj);

  (3) to achieve normal function conversion function or static member function CPoint function, the way to achieve diversity. The pseudo-code: CPoint GetPointFromRect (const CRect & obj); or void GetPointFromRect (CRect & obj) and the like.

(4) A very strange. Another use operator, in addition to the overload overload category symbol. Both operator CPoint (); This overloaded to use to achieve the CPoint CRect class.

Note that a small detail in the overloaded constructors CPoint which CRect parameter, and the operator CPoint CRect achieved implicit conversion. When calling the constructor CPoint preferred, followed by re-invoke implicit conversion function CPoint of the CRect.

Fake code:

CTestRect test(2,3, 20,50);

CTestPoint obj,obj3;

obj = (CTestPoint)test; // what function?

obj3 = test;

CTestPoint obj2 = test;

Guess you like

Origin www.cnblogs.com/lu-ping-yin/p/10992751.html