运算符的重载实际是一种特殊的函数重载,必须定义一个函数,并告诉C++编译器,当遇到该重载的运算符时调用此函数。这个函数叫做运算符重载函数,通常为类的成员函数。
定义运算符重载函数的一般格式:
返回值类型 类名::operator重载的运算符(参数表) {……}
operator是关键字,它与重载的运算符一起构成函数名。因函数名的特殊性,C++编译器可以将这类函数识别出来。
实例:重载复数运算中运算符号+
Complex operator+(const Complex& cx) const
{
Complex tmp(Real + cx.Real, Image + cx.Image);
return tmp;
// return Complex(Real + cx.Real, Image + cx.Image);
}
重载=
在类定义中如果没有显式给出赋值运算符重载函数时,并不是不用赋值函数,而是由系统自动调用缺省的赋值函数。
class Int {
private:
int value;
public:
Int(int x = 0) :value(x){
value = x;
cout << "Create Int" << value << endl;
}
~Int() {
cout << "Destory Int" << value << endl;
value = -1;
}
Int(const Int &it) :value(it.value) {
cout << "Copy Creat Int" << value << endl;
}
//void operator=(Int *const this,const Int &it)
void operator= (const Int & it){//operator 赋值运算符
if(this != &it){//判断不是本身给本身赋值
this->value = it.value;//赋值
}
}//c = b; //c.operator=(b);
// operator=(&c,b)
};
int main() {
Int a(10);
Int b(a);
Int& c = a;
c.operator=(b);//赋值运算符重载
return 0;
}
在此基础上我们可以实现连续赋值:
class Int {
private:
int value;
public:
Int(int x = 0) :value(x) {
value = x;
cout << "Create Int" << value << endl;
}
~Int() {
cout << "Destory Int" << value << endl;
value = -1;
}
Int(const Int &it) :value(it.value) {
cout << "Copy Creat Int" << value << endl;
}
//加& 引用 使生存周期为主函数
Int & operator= (const Int & it){
if (this != &it) {
this->value = it.value;//赋值
}
return *this;
}//c = b; //c.operator=(b);
// operator=(&c,b)
};
int main() {
Int a, b, c(10);
a = b = c;//调动两次赋值引用
return 0;
//a = b = c;
//a = b.operator=(c);
//a = operator(&b,c); //error //返回值为无类型
}
运算符重载函数的总结
1、运算符重载函数的函数名必须为关键字operator加一个合法的运算符。在调用该函数时,将右
操作数作为函数的实参。
2、当用类的成员函数实现运算符的重载时,运算符重载函数的参数(当为双目运算符时)为一个
或(当为单目运算符时)没有。运算符的左操作数一定是对象,因为重载的运算符是该对象的成员函数,而右操作数是该函数的参数。
3、单目运算符“++”和“--”存在前置与后置问题。
前置“++”格式为:
返回类型 类名::operator++(){……}
而后置“++”格式为:
返回类型 类名::operator++(int){……}
后置“++”中的参数int仅用作区分,并无实际意义,可以给一个变量名,也可以不给变量名。
4、C++中只有极少数的运算符不允许重载
还有 # , ## , // , / * */
重载运算符有以下几种限制
不可臆造新的运算符.
不能改变运算符原有的优先级、结合性和语法结构,不能改变运算符操作数的个数.
运算符重载不宜使用过多.
重载运算符含义必须清楚,不能有二义性.