一,基本认识
1,利用operator关键字对操作符重载,本质是对函数的重载
2,friend可以对函数或类开放访问权限。(可以访问private)
3,对<<运算符重载时,返回值类型要是ostream的引用,主要目的是链式访问
cout<<c1<<c2<<endl;为了可以连续这样访问
二,加深认识
1,对于类来说操作符重载既可以用友员函数重载也可以用成员函数重载
2,成员函数重载,少一个左参数,不要friend
3,重载方式的选择
-
- 当无法修改左参数时,使用全局函数重载(友员函数)<<和>>只能用友员函数重载
- =,[],(),->只能用成员函数重载
- . ,.*,::,sizeof,?: 不能重载
- 一般单目和复合重载为成员函数,双目重载为友员
4,++重载的问题
后置++ 用一个占位符区别前置++
Complex operator++ (int);
Complex& operator++();
5,&&和||重载的问题
&&和||在语法上可以重载,但是不要去重载,无法实现短路原则。因为那些函数参数都会被求值。
6,重载符重载返回值问题
如果是栈对象就不能是引用,如果返回的是带引用的参数,则返回类型也是引用。对于*this也返回其引用。
7,重载实例
#include <iostream>
using namespace std;
class test
{
private:
int a;
int b;
public:
test(int i,int j):a(i),b(j)
{
}
test& operator ++();//前置++
test operator ++(int);//后置++
test& operator -();
test operator +(const test& c2);//成员函数重载
//friend test operator +(const test& c1,const test& c2);//使用引用的原因是避免了拷贝。
friend ostream& operator <<(ostream &out,const test& c);//返回值使用ostream&的原因是<<能够连续输出
};
/*
test operator +(const test& c1,const test& c2)
{
test ret(0,0);
ret.a=c1.a+c2.a;
ret.b=c1.b+c2.b;
return ret;
}
*/
test& test::operator -()
{
this->a=-this->a;
this->b=-this->b;
return *this;
}
test& test::operator ++()//前置++
{
++this->a;
++this->b;
return (*this);
}
test test::operator ++(int)//后置++ 。为什么返回值不能是引用 ,ret对象是栈上的对象。
{
test ret=(*this);
this->a++;
this->b++;
return ret;
}
test test::operator +(const test& c2)
{
test c(0,0);
c.a=this->a+c2.a;
c.b=this->b+c2.b;
return c;
}
ostream& operator <<(ostream &out,const test& c)
{
cout<<c.a<<"+"<<c.b<<"i";
return out;
}
int main(void)
{
test c1(1,2);
test c2(1,2);
test c3(c1+c2);// test c3=c1+c2;
//友员重载等价于operator +(c1,c2) ;成员函数重载等价于 c1.operator+(c2);
cout<<c1<<endl;//operator <<(cout,c1)
cout<<c2<<endl;
cout<<c3<<endl;
cout<<++c1<<endl;//c1.operator ++()
cout<<c2++<<endl;//c2.operator ++(int)
cout<<-c3<<endl;//c3.operator -();
return 0;
}