一、为什么重载操作符?用其他函数不可以么?
解析: 使用重载操作符,可以令程序更自然、更直观,方便其他人功能容易理解自己写的程序。 当然其他函数也可以,但是为了更直观,建议使用操作符重载。(想想自己写了一堆代码,要是不用操作符重载,在让别人纠错或者维护的时候,是不是大大增加了阅读的难度。)
- 简单解释:重载就是重新赋予新的含义,这里就是给操作符在原来的功能上赋予新的含义,以满足用户需求
- 认识:重载操作符是具有特殊函数名的函数,关键字operator后面接需要定义的操作符符号。操作符重载也是一个函数,具有返回值和形参表。
- 使用格式: 返回类型 operator 操作符(参数列表) { 对操作符的重载处理 }
二、有哪些操作符可以重载?
重载的规则:
1、只有C++预定义的操作符才可以被重载;
2、对于内置类型的操作符,它的预定义不能改变,即不能改变操作符原来的功能;
3、重载操作符不能改变他们的操作符优先级;
4、重载操作符不能改变操作数的个数;
5、除了对()操作符外,对其他重载操作符提供缺省实参都是非法的。
举例:
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(double real = 0.0 , double image = 0.0)
{
cout<<"Complex(double real , double image ) "<<endl;
_real=real;
_image=image;
}
Complex(const Complex& c)
{
_real=c._real;
_image=c._image;
}
~Complex( )
{
cout<<"~Complex()"<<endl;
}
//调用过程:bool operator==(Complex const *this,const Compex& c)
bool operator==(const Complex& c) //重载= =
{
return (_image==c._image)&&(_real==c._real);
}
Complex& operator=(const Complex& c)
{
if(this==&c)
{
_real=c._real;
_image=c._image;
}
return *this ;
}
bool operator>(const Complex& c)
{
return _real>c._real;
}
private:
double _real;
double _image;
};
//测试
int main()
{
Complex c1;
Complex c2(c1);
c1==c2; //调用过程 c1.operator==(&c1 ,c2);
return 0 ;
}
使用注意:
1、当返回值不是本函数内定义的局部变量时就可以返回一个引用。在通常情况下,引用返回值只用在需对函
数的调用重新赋值的场合,也就是对函数的返回值重新赋值的时候。(以重载赋值= 为例!)
如果返回值:返回的局部对象,在赋值语句结束之后释放,函数返回时保存的临时变量为该对象;
如果返回引用:返回的局部对象,在函数返回时释放,函数返回时保存的临时变量为该对象的引用(地址);
2、在增量运算符中,放上一个整数形参,就是后增量运行符,它是值返回,对于前增量没有形参,而且是引用返回。
举例:
class Test
{
public:
Test(int x = 3)
{
m_value = x;
}
Test& operator++(); //前增量
Test operator++(int);//后增量
private:
int m_value;
};
Test& Test::operator++()
{
m_value++; //先增量
return *this; //返回当前对象
}
Test Test::operator++(int)
{
Test temp(*this); //创建临时对象
m_value++; //再增量
return temp; //返回临时对象
}