码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 课时32 运算符重载-赋值

时间:2015-09-22 18:09:16      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

#include <iostream>
using namespace std; class Fi{ public: Fi(){cout<<"Fi::Fi()"<<endl;} }; class Fee{ public: Fee(int){cout<<"Fee::Fee(int)"<<endl;} Fee(const Fi&){cout<<"Fee::Fee(Fi&)"<<endl;} Fee& operator=(const Fee& rhs){ cout<<"Fee::operator="<<endl;
if(this!=&rhs){ //perform assignment}
         return *this; } };
int main(){ Fee fee=1; //Fee(int) Fi fi; Fee fum=fi; //Fee(Fi); fum=fi; //先用fi构造出一个Fee对象,再调用赋值运算 }

运行结果:

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

 

1、Copying vs. Initialization

   MyType b;

   MyType a = b;  //拷贝构造

   a = b;              //赋值

 

2、Automatic operator= creation

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

    memberwise assignment 

 

3、运算符重载-赋值:必须为成员函数,对自己赋值并返回自己

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

以下例子说明为什么需要判断 this!=&rhs

class A{
    char *p;
    A& operator=(const A& that){
        delete p;  
        p=new [strlen(that.p)+1]; //若自己赋值自己,that.p已经被delete;
        strcpy(p,that.p);
        return *this;
    }
}

 

4、For classes with dynamically allocated memory declare an assignment operator (and a copy constructor)

 

 

--以上内容摘自 《面向对象程序设计C++课程(翁凯)》

 

C++ 课时32 运算符重载-赋值

标签:

原文地址:http://www.cnblogs.com/null2/p/4829304.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!