1 / 6

14.3

Memberwise Assignment. 14.3. Memberwise Assignment. Can use = to assign one object to another, or to initialize an object with an object ’ s data Copies member to member. e.g. , instance2 = instance1; means:

shea
Télécharger la présentation

14.3

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Memberwise Assignment 14.3

  2. Memberwise Assignment • Can use = to assign one object to another, or to initialize an object with an object’s data • Copies member to member. e.g., instance2 = instance1; means: copy all member values from instance1 and assign to the corresponding member variables of instance2 • Use at initialization: Rectangle r2 = r1;

  3. Declare the Class my_string class MyString{ public: MyString(int n); MyString(const char * str); ~ MyString(); int length() const ; //const member function void print() const; private: char * s; int len; };

  4. // // Assignment of a Mystring into another Mystring // Mystring& Mystring::operator=(const Mystring& mstr) { // ("Mystring assignment operator”) if (&mstr == this) { //("Not copying myself"); return *this; } // Delete the old string that this class was holding. delete [] s; // Allocate enough space for the new string. s = new char[mstr.length() + 1]; // Copy the new string into myself strcpy(s, mstr.s); // Return myself return *this; }

More Related