标签:return ++ age 运算符 重载 operator class
1.重载左移运算符 不能利用成员函数重载,因为无法实现cout在左侧
ostream & operator<<(ostream &out,Person &p) 对cout起别名out
{
out<<"m_a="<<m_a<<" m_b="<<m_b;
return out;
}
2.重载前置++运算符 返回引用为了多次对一个数据递增
animal& operator++()
{
m_num++;
return *this;
}
3.重载后置++运算符
animal operator(int)
{
animal temp=*this;
m_num++;
return temp;
}
4.重载赋值运算符
Person& operator=(Person &p)
{
if(m_age!=NULL;
{
delete m_age;
m_age=NULL;
}
m_age=new int (*p.m_age); m_age=p.m_age;
编译器提供的代码是浅拷贝
return *this;
}
5.关系运算符重载
bool operator!=(Person &p)
{
if(this->m_name == p.m_name &&this->m_age ==p.m_age)
return false;
else
return true;
}
6.函数调用运算符重载
由于重载后使用方式非常像函数的调用,因此称为仿函数。其没有固定写法,十分灵活。
void operator()(string a)
{
cout<<a<<endl;
}
调用时:
MyPrint myPrint;
myPrint("hello world");
也可以这样匿名函数对象:
MyPrint()("hello world");
标签:return,++,age,运算符,重载,operator,class 来源: https://blog.csdn.net/wanxiangzx/article/details/121146476
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。