通俗的讲,运算符重载就是把运算符赋予新的功能,比如说 + 有整数相加 浮点数相加的功能,但是没有复数相加的功能,这时我们通过运算符重载,使得 + 具有复数相加的功能,这就叫做运算符重载,本质上, 运算符重载是函数的重载。
重载运算符使具有特殊名称的函数, 形式如下:
1 返回类型 operator运算符号(形式参数列表) 2 { 3 函数体 4 }
1 operator后接需要重载的运算符, 成为运算符函数。
2 运算符函数的函数名就是“ operator运算符号” //operator+ 是函数名
下面通过设计一个复数类实现 + 的重载
1 #include <iostream> 2 using namespace std; 3 class complex //复数类 4 { 5 public: 6 complex(double r=0.0,double i=0.0)//构造函数 {real=r; imag=i; } 7 complex operator +(complex &c2); //重载+运算符 8 complex operator -(complex &c2); //重载-运算符 9 void display() 10 { 11 cout<<real<<"+"<<imag<<"i"<<endl; 12 } 13 private: 14 double real; //实部 15 double imag; //虚部 16 };
complex complex::operator +(complex &c2) 18 { complex c; 20 c.real=c2.real+real; 21 c.imag=c2.imag+imag; 22 return c; 23 } 24 complex complex::operator -(complex &c2) 25 { complex c; 27 c.real=real-c2.real; //顺序不能颠倒 28 c.imag=imag-c2.imag; 29 return c; 30 } 31 int main() 32 { complex c1(1,2),c2(3,4),c3; 34 c3=c2+c1; c3.display(); //输出4+6i 36 c3=c2-c1; c3.display(); //输出2+2i 38 return 0; 39 }
只有类的普通成员函数才有this指针 类的有元函数 静态成员函数都是没有this指针的
当运算符重载为友元函数时, 运算符函数的形式参数的个数和运算符规定的运算对象个数一致 一般我们也是采用这种方式
形式如下:
class 类名{ //类体
……
//友元声明
friend 返回类型 operator 运算符号(形式参数列表);
};
返回类型 operator 运算符号(形式参数列表)
{
函数体
}
还是以 + - 运算符为例
1 #include <iostream> 2 using namespace std; 3 class complex //复数类 4 { 5 public: 6 complex(double r=0.0,double i=0.0) {real=r; imag=i;}//构造函数 7 friend complex operator +(const complex &c1,const complex &c2); //重载+运算符 8 friend complex operator -(const complex &c1,const complex &c2); //重载-运算符 9 void display() 10 { cout<<real<<"+"<<imag<<"i"<<endl; } 11 private: 12 double real; //实部 13 double imag; //虚部 14 }; 15 complex operator +(const complex &c1,const complex &c2) 16 { complex c3; 17 c3.real=c1.real+c2.real; 18 c3.imag=c1.imag+c2.imag; 19 return c3; 20 } 21 complex operator -(const complex &c1,const complex &c2) 22 { complex c3; 23 c3.real=c1.real-c2.real; 24 c3.imag=c1.imag-c2.imag; 25 return c3; 26 } 27 int main() 28 { complex c1(1,2),c2(3,4),c3; 29 c3=c2+c1; c3.display(); //输出4+6i 30 c3=c2-c1; c3.display(); //输出2+2i 31 return 0; 32 }
重载运算符的规则
►( 1) C++绝大部分的运算符可以重载, 不能重载的运算符有:. .* :: ?: sizeof
►( 2) 不能改变运算符的优先级、 结合型和运算对象数目。
►( 3) 运算符重载函数不能使用默认参数。
►( 4) 重载运算符必须具有一个类对象( 或类对象的引用) 的参数,不能全部是C++的内置数据类型。
►( 5) 一般若运算结果作为左值则返回类型为引用类型; 若运算结果要作为右值, 则返回对象。
►( 6) 重载运算符的功能应该与原来的功能一致。