The difference between C ++ and C # construct functions

zhaozj2021-02-16  124

(1) C is not allowed to call another constructor (called delegation constructor call) in a constructor, while C # is allowed. E.g:

C :

Struct Point {public: int x, y; point (int x, int y); Point (Point PT): Point (pt.x, pt.y) {} // error, C is not allowed};

C #:

Struct Point {public INT X, Y; PUBLIC POINT (INT X, INT Y); PUBLIC POINT (POINT PT): Point (pt.x, pt.y) {} // can, C # Allow};

Delegating constructor calling syntax very natural and easy to understand, so you may question C does not provide it to add trouble to programmers. In fact, C does not provide this feature is not for grammar considerations, but for resource management (, there are many things for C ). We know that the C constructor is used to assign resources, and the destructor is used to release resources, constructor, and destructor calls must match, otherwise it breaks the basic rules of C . If the delegation constructor is allowed, it will obviously break this rule - the constructor is executed twice, and the destructor is only executed once. Of course, this is not a problem for some classes, such as the previous point, but this feature may belong to the characteristics of "danger" from the perspective of language mechanism. Note: In the draft C standard proposal, Herb et al. Has a proposal to allow delegation constructors, of course, to a large extent, for the convenience of C / CLI bindings.

(2) In the C constructor, the virtual function call is automatically converted to a normal function call by the compiler, and the virtual function call is allowed in the C # constructor. C handles naturally have it - in C , the constructor is initialized after the completion of the completion, and for the polymorphic object, it means that the constructor has implemented a very important thing - initialization The virtual function table of the object. If we call the virtual function in the constructor of the base class, because the virtual function table of the object is still the virtual function table of the base class, the correct virtual function call cannot be performed. This is the reason, usually we should avoid calling the virtual function in the constructor because it violates the semantics of the virtual function. In C #, the type information of the object's constructor is initialized, so it is possible to perform normal virtual function calls.

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

New Post(0)