C + + Class 32 operator overloading-assignment

Source: Internet
Author: User

#include <iostream>
using namespacestd;classfi{ Public: Fi () {cout<<"Fi::fi ()"<<Endl;}};classfee{ Public: Fee (int) {cout<<"fee::fee (int)"<<Endl;} Fee (Constfi&) {cout<<"Fee::fee (fi&)"<<Endl;} fee&operator=(Constfee& RHS) {cout<<"fee::operator="<<Endl;
if (THIS!=&RHS) {//perform Assignment}
return *this; }};intMain () {Fee Fee=1;//Fee (int)fi fi; Fee Fum=fi;//Fee (Fi);Fum=fi;//first, a fee object is constructed with fi, and then the assignment operation is called.}

Operation Result:

Fee::fee (int) Fi::fi () Fee::fee (fi&) Fee::fee (fi&) Fee::operator =

1, Copying vs. initialization

MyType b;

MyType a = b; Copy Construction

A = b; Assign value

2, Automatic operator= creation

The compiler would automatically create a type::operator= (type) if you don ' t make one.

memberwise Assignment

3, Operator overloading-assignment: must be a member function, assign yourself a value and return yourself

t& T::operator= (const t& RHS) {    //check for self assignment    if(this!=&rhs) {        //perform assignment     }     return *this;}

The following example shows why you need to judge THIS!=&RHS

class a{    Char *p;    Aoperator= (const a& that ) {        delete  p;          P=new [Strlen (THAT.P) +1// If you assign yourself, THAT.P has been deleted;         strcpy (P,THAT.P);         return *this;    }}

4. For classes with dynamically allocated memory declare an assignment operator (and a copy construct or)

--The above content is from "object-oriented Programming C + + course (Onke)"

C + + Class 32 operator overloading-assignment

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.