Overloaded assignment operators

Source: Internet
Author: User

The following points should be noted:

1. Whether to declare the return value type as a reference to that type, or not to make successive assignments

2. Whether the passed parameter is declared as a constant reference , if it is not a constant, there is no guarantee that the passed argument will not be modified, and if it is not a reference, the copy constructor is called once to affect the efficiency of the Code.

3. Determines whether the two operands that are assigned are the same instance .

4. Whether to delete the memory of the assigned object, otherwise a memory leak will occur.

The program code is as follows:

#include <iostream>#include<cstring>using namespacestd;classmystring{ Public: Mystring&operator=(ConstMystring &str); Mystring (Char*pdata=null)//constructors with default values{Data=pdata; } Mystring (ConstMystring &str)//copy Constructor{Data=Str.data; }    ~mystring ()// Destructors    {    }    voidShow () {cout<<data<<Endl; }Private:    Char*data;}; Mystring&mystring::operator=(ConstMystring &str) {    if(&str!= This)//If the &str==this does not have to be assigned a value    {        DeleteData//release the original space firstData=NULL; Data=New Char[Strlen (Str.data) +1];//initializing space for pointersstrcpy (Data,str.data);//Assign Value    }    return* This;}intMain () {Mystring str1 ("Hello"), str2;//declaring two classes of objectsstr1.show (); STR2=STR1;//calling a custom assignment methodstr2.show (); STR1=STR1;//assign yourself a valuestr1.show (); return 0;}

Overloaded assignment operators

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.