小学生早恋吧,黑骨木,北方影院变脸惊情
=
重载等号只能重载为成员函数
赋值语句和初始化语句的等号=
含义不同,初始化语句需要用构造函数实现
同类赋值注意点(可能包含指针)
浅拷贝:采用默认的赋值号,导致指针指向同一个地址,原有动态分配内存未释放,且数据相互影响
深拷贝:释放原有内存空间,并重新动态分配一块内存
在拷贝前应检查是否拷贝自身(即if(this=&s)
,会造成自身内部空间先被是否,复制出错),是则直接return *this
返回值应为classname&
,void
和classname
有缺陷
a=b=c; //连续赋值,void不行 (a=b)=c; //结果为a=c; classname不行
使用复制拷贝函数时,需要考虑类似的问题
string& string::operator= (const string &s){ if(this==&s) return *this; if(str) delete [] str; if(s.str==null){ str=null; }else{ str=new char[strlen(s.str)+1]; strcpy(str,s.str); } return *this; }
cout
和cin
分别是ostream
和istream
类的对象,类中分别对<<
和>>
运算符进行了重载
可全局重载>>
和<<
运算符,使其满足要求
ostream& operator << (ostream &os,const complex &c){ os<<c.real<<"+"<<c.imag<<"i"; return os; } istream& operator >> (istream &is,complex &c){ string s; is>>s; int pos=s.find('+',0); string substr=s.substr(0,pos); c.real=stod(substr); int pos2=s.find('i',0); c.imag=stod(s.substr(pos+1,pos2)); return is; }
不写返回值(返回值即转换类型)
定义为成员函数时,无参数
class complex{ double real,imag; public: complex(double r=0,double i=0):real(r),imag(i){}; operator double (){ return real; } //将complex类强制转换成double类 };
包含了显式类型转换和自动类型转换
complex c(1.2,3.4); cout<<(double) c<<endl; double tmp=5+c; cout<<tmp<<endl;
前置(作为一元运算符处理),返回值为引用
//成员函数 t& operator++(); t& operator--(); //普通函数 t& operator++(t& c); t& operator--(t& c);
后置(作为二元运算符处理),返回值不是引用,效率没前置的高
//成员函数 t operator++(int); t operator--(int); //普通函数 t operator++(t& t,int); t operator--(t& t,int);
示例
cdemo& operator--(cdemo &c){ c.n--; return c; } cdemo operator--(cdemo &c,int){ cdemo tmp(c); c.n--; return tmp; }
.
,.*
,::
,?:
,sizeof
()
,[]
,->
,或赋值运算符=
时,运算符重载函数必须声明为类成员函数运算符重载时,应尽量保留运算符原有的特性
不能被赋值
成员函数参数个数=操作数-1
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
如何在没有core文件的情况下用dmesg+addr2line定位段错误
用QT制作3D点云显示器——QtDataVisualization
网友评论