1.重载左移运算符 不能利用成员函数重载,因为无法实现cout在左侧
ostream & operator<<(ostream &cout,Person &p) //因为cout全局只能有一个,所有要么引用cout,要么对cout起别名out,ostream &out
{
out<<"m_a="<<m_a<<" m_b="<<m_b;
return cout;
}
//使用ostream返回值类型是为了体现链式编程思想
2.重载前置++运算符 返回引用为了多次对一个数据递增
class animal
{
public:
animal& operator++() //如果不返回引用,则实际是返回了一个局部变量animal
{
m_num++;
return *this;
}
animal operator(int) //后置递增,注意((n++)++)本来就是错的
{
animal temp=*this;
m_num++;
return temp;
}
int m_num;
}
3.重载后置++运算符
4.重载赋值运算符
其实c++本身就会重载赋值运算符,只不过和自带的拷贝构造函数一样,是简单的值拷贝,如果有数据存在堆区,就会造成堆区内存重复释放的问题,此时便需要自己重载赋值运算符
calss Person
{
public:
Person& operator=(Person &p) //返回值为Person是链式编程思想,加引用时为了返回真正的对象
{
if(m_age!=NULL;
{
delete m_age;
m_age=NULL;
}
m_age=new int (*p.m_age); //m_age=p.m_age; 编译器提供的代码是浅拷贝
return *this;
}
int *m_age;
}
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");
类型名加小括号是定义了一个匿名函数对象,特点是当前行执行完后立即被释放