标签:
#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++课程(翁凯)》
标签:
原文地址:http://www.cnblogs.com/null2/p/4829304.html