运算符重载的意义
给自定义类型写一个成员方法,让指定的运算符按照我们希望的逻辑进行运算
一元运算符
“ * ”运算符
“ ++”运算符
“ --”运算符
自加运算符“++”的重载
前置加加
Complex& operator++()//前置++,先自加再返回值
{
++_a;
return *this;//当出了函数体,*this是依然存在的,所以可以返回引用
}
++c1;
cout << "c1:"<<c1 << endl;
后置加加
Complex operator++(int )//后置++,先返回值再自加。参数加int没有实际作用,只是为了让编译器进行区分
{
int tmp = _a;
++_a;
return Complex(tmp,_b);//因为构造的是临时对象,只能返回对象,而不能返回引用。因为当出了函数体临时对象就没有了,如果可以返回引用就相当于返回了一个野指针
}
Complex c4=c1++;
cout << "c1++:" << c4 << endl;
二元运算符
“ + ,- ,= ,&& ,|| ,<< , >> ”
输出运算符“ << ”的重载
定义ostream类对象cout的引用:
ostream& oo = cout;//ostream是一个类,该语句的意思是定义一个变量oo是cout的引用
//ostream只有一个对象,但是可以定义引用
oo << s3 << endl;
输出运算符的重载:
void operator << (/* this */ostream& out)
{
out << _a << "+" << _b << "i" << endl;
}
输出运算符的调用:不方便,类似于一个show()方法,show方法不用指定参数,此处还需要指定参数
c1.operator<<(cout);
改进1:将输出运算符的重载写在类外。因为需要改变参数的位置,而类内第一个参数默认为this指针
friend void operator << (ostream& out,const Complex& src);//_a和_b是私有,所以要设置为友元
void operator << (ostream& out,const Complex& src)
{
out << src._a << "+" << src._b << "i" << endl;
}
不能进行连续输出:
cout << c1 ;//第一个参数:cout;第二个参数:c1
改进二:返回值为引用
friend ostream& operator << (ostream& out, const Complex& src);
ostream& operator << (ostream& out, const Complex& src)
{
out << src._a << "+" << src._b << "i" << endl;
return out;
}
cout << c1 << endl;
输入运算符“>>”的重载
friend istream& operator >> (istream& in, Complex& src);
istream& operator >> (istream& in, Complex& src)
{
in>> src._a;
in>> src._b;
return in;
}
三元运算符
” :?“