tailieunhanh - C++ Weekend Crash Course phần 9

nhiên, điều này sử dụng bản sao các nhà xây dựng ít rõ ràng hơn, điều này cũng gọi các nhà xây dựng bản sao này tạo ra một đối tượng mặc định và sau đó ghi đè lên nó với đối số thông qua | 410 Sunday Afternoon void fn MyStruct source destination destination source However this default definition is not correct for classes that allocate resources such as heap memory. The programmer must overload operator to handle the transfer of resources. Comparison with copy constructor The assignment operator is much like the copy constructor. In use the two look almost identical void fn MyClass mc MyClass newMC mc of course this uses the copy constructor MyClass newerMC mc less obvious this also invokes the copy constructor MyClass newestMC this creates a default object newestMC mc and then overwrites it with the argument passed The creation of newMC follows the standard pattern of creating a new object as a mirror image of the original using the copy constructor MyClass MyClass . Not so obvious is that C allows the second format in which newerMC is created using the copy constructor. However newestMC is created using the default void constructor and then overwritten by mc using the assignment operator. The difference is that when the copy constructor was invoked on newerMC the object newerMC did not already exist. When the assignment operator was invoked on newestMC it was already a MyClass object in good standing. The rule is this The copy constructor is used when a new object is being created. The assignment operator is used if the lefthand object already exists. Session 28 The Assignment Operator 411 Like the copy constructor an assignment operator should be provided whenever a shallow copy is not appropriate. Session 20 has a full discussion of shallow versus deep constructors. It suffices to say that a copy constructor and an assignment operator should be used when the class allocates and saves resources within the class so that you don t end up with two objects pointing to the same resource. How Do I Overload the Assignment Operator 20 Min. To Go Overloading the assignment operator is similar to overloading any other operator. For example Listing 28-1 is .

TỪ KHÓA LIÊN QUAN