重新定义运算符的功能,不使用默认功能
1.运算数的数量不变
2.运算符的优先级不变
3.部分运算符(. .* :: ?: sizeof typeid)等不能重载
4.没有的运算符不能重载
5.必须在一个类中或枚举类型中
作为成员函数:
const String String::operator+(const String& that);
运算符左边叫recevicer,由recevicer的类型决定运算符
class Integer{
public:
Integer(int n=0):i(n){}
//可以使用内联进行优化
const Integer operator+(const Integer& n) const{
return Integer(i +n.i ); //运算符不会改变两个算子的值,返回值不能做左值也用const
}
private:
int i;
};
Integer x(1),y(5),z;
z=x+y; //可以,两个integer对象
z=x+3; //可以,用构造函数将3构成一个integer的对象
z=3+y; //不可以,3决定用整数的+来做运算,+没有被重载
z=x+3.5; //不可以,3.5无法自动转换成整数
z=x+(int)3.5;
单目运算符不需要传值,双目运算符必须有一个参数
作为global(free) function:
需要传入两个参数(通过get或者friend来实现)作为算子,两个算子都有类型转换
const String operator+ (const String& r,const String& l);
z=3+x; //可以,3作为整数加法无法做,但作为intger可以做
z=3+7; //可以,将10转为一个inter对象
tips:
1.单目最好做成成员函数
2.= () [] -> ->*必须做成成员函数
3.其他双目作为全局函数
运算符原型:
参数:传递的参数一定是对象即引用,若运算符会修改算子(++,--等)不用加const,不会修改加const,成员函数中this的const加在函数参数表之后
返回值:取决于运算符的意义,如+ - 等需要有一个const的对象来接受返回值,如=因为是改变自身的值,即返回自身的引用,并且不能加const
const T operator+(const T& l,const T& r)const; //+-*/%^&|~
bool operatorX(const T& l,const T& r)const; //!&&||< <=
T& T::operator[](int index); //[]
class Integer{
public:
//int用于区分a++和++a
const Integer& operator++(); //++a
const Integer operator++(int); //a++
const Integer& operator--(); //--a
const Integer operator--(int); //a--
}
const Integer& Integer::operator++(){
*this +=1;
return *this;
}
const Integer Integer::operator++(int ){
Integer old(*this);
++(*this);
return old;
}
关系运算符:只定义==和< ,气筒运算符通过==和<来定义,这些函数都是inline没有性能损失。方便以后更改运算符行为。
bool Integer::operator==(const Integer& rhs)const{
return i==rhs.i;
}
bool Integer::operator!=(const Integer& rhs)const{
return !(*this==rhs);
}
bool Integer::operator<(const Integer& rhs)const{
return i<rhs.i;
}
bool Integer::operator>(const Integer& rhs)const{
return rhs<*this;
}
bool Integer::operator<=(const Integer& rhs)const{
return !(rhs<*this);
}
bool Integer::operator>=(const Integer& rhs)const{
return !(*this<rhs);
}
[]:
class Vector{
public:
Vector(int size):m_size(size){
m_array=new int[size];
}
~Vector(){delete m_array;}
int& operator[](int index){return m_array[index];}
private:
int m_size;
int *m_array;
}