Assignment between base classes and derived objects

zhaozj2021-02-16  101

Class a {} class b: public a {} a a a an AObject; b bobject;

related

(1) aboject = bobject;

(2) BOBJECT = Aboject;

instruction of.

============================================================================================================================================================================================================= ==================================== (1) aobject = bobject; call the default a :: operator =, automatically generated by the compiler, it The function declaration is roughly similar to: a operator = (a rhs), anyway, the right side of the right side is an object, BOBJECT as a sub-class object of A is also possible, but "truncation" is generated during transmission.

(2) BOBJECT = AObject; calls default b :: operator =, it is also automatically generated by the compiler, its function declaration is roughly similar to: b operator = (b rhs), here is the right side of the right side, AOBJECT It is not feasible at this time.

At this time, single overload B :: operator = doesn't help, because you can't change the operator = function parameter must be this fact of B object. To implement bobject = aObject; you can overload the mandatory type conversion function, you can also use the compiler implicit type conversion capability, such as Class a {public: a () {}};

Class B: Public a {public: b () {} b (a a a a)}};

INT main () {aObject = bobject; bobject = aobject; return 0;

PS: This is a question I am in the 9CBS forum, thanks to the answer of netizens such as rookiestar (★) (Barbaroa).

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

New Post(0)