C ++ 中预定义的运算符的操作对象只能是基本数据类型。但实际上,对于许多用户自定义类型(例如类),也需要类似的运算操作。这时就必须在C ++ 中重新定义这些运算符,赋予已有运算符新的功能,使它能够用于特定类型执行特定的操作。运算符重载的实质是函数重载,它提供了C ++ 的可扩展性,也是C ++ 最吸引人的特性之一。
运算符重载是通过创建运算符函数实现的,运算符函数定义了重载的运算符将要进行的操作。运算符函数的定义与其他函数的定义类似,惟一的区别是运算符函数的函数名是由关键字 operator和其后要重载的运算符符号构成的。运算符函数定义的一般格式如下:
< 返回类型说明符 > operator < 运算符符号 > ( < 参数表 > )
{
<函数体>
}
运算符重载时要遵循以下规则:
( 1 ) 除了类属关系运算符 " . " 、成员指针运算符 " .* " 、作用域运算符 " :: " 、sizeof运算符和三目运算符 " ?: " 以外,C ++ 中的所有运算符都可以重载。
( 2 ) 重载运算符限制在C ++ 语言中已有的运算符范围内的允许重载的运算符之中,不能创建新的运算符。
( 3 ) 运算符重载实质上是函数重载,因此编译程序对运算符重载的选择,遵循函数重载的选择原则。
( 4 ) 重载之后的运算符不能改变运算符的优先级和结合性,也不能改变运算符操作数的个数及语法结构。
( 5 ) 运算符重载不能改变该运算符用于内部类型对象的含义。它只能和用户自定义类型的对象一起使用,或者用于用户自定义类型的对象和内部类型的对象混合使用时。
( 6 ) 运算符重载是针对新类型数据的实际需要对原有运算符进行的适当的改造,重载的功能应当与原有功能相类似,避免没有目的地使用重载运算符。
#include <iostream>
using namespace std;
class Point{
public:
Point(){};
Point (int x, int y): x(x),y(y) {};
Point operator+(const Point &a){ //类内重载,运算符重载函数作为类的成员函数
Point ret;
ret.x = this->x + a.x;
ret.y = this->y + a.y;
return ret;
}
int x,y;
};
int main() {
Point a(2,4),b(5,3);
Point c = a + b;
cout<< "x :" << c.x << endl;
cout<<"y :" << c.y << endl;
}
类外重载如下
#include <iostream>
using namespace std;
class Point{
public:
Point(){};
Point (int x, int y): x(x),y(y) {};
friend Point operator+(const Point &, const Point &);
int x,y;
};
Point operator+(const Point &a,const Point &b){//类外重载,运算符重载函数作为类的友元函数
Point ret;
ret.x = a.x + b.x;
ret.y = a.y + b.y;
return ret;
}
int main() {
Point a(2,4),b(5,3);
Point c = a + b;
cout<< "x :" << c.x << endl;
cout<<"y :" << c.y << endl;
}
友元运算符重载函数
#include<iostream>
2 using namespace std;
3 class Complex
4 {
5 public:
6 Complex(double r=0.0,double i=0.0);
7 void print();
//friend为友元函数的关键字,这两个符号运算符重载函数的参数类型至少有一个类类型或者类的引用
8 friend Complex operator+(Complex &a,Complex &b);
9 friend Complex operator-(Complex &a,Complex &b);
10 private:
11 double real;
12 double imag;
13 };
14 Complex::Complex(double r,double i) //在类外定义函数,需要用::作用域符号
15 {
16 real = r;
17 imag = i;
18 }
19 Complex operator+(Complex &a,Complex &b)
20 {
21 Complex temp; //创建一个临时对象
22 temp.real = a.real + b.real;
23 temp.imag = a.imag + b.imag;
24 return temp;
25 }
26 Complex operator-(Complex &a,Complex &b)
27 {
28 Complex temp; //创建一个临时对象
29 temp.real = a.real - b.real;
30 temp.imag = a.imag - b.imag;
31 return temp;
32 }
33 void Complex::print()
34 {
35 cout<<real;
36 if(imag>0) cout<<"+";
37 if(imag!=0) cout<<imag<<'i'<<endl;
38 }
39 int main(int agrs,const char *agrv[])
40 {
41 Complex A1(2.3,4.6),A2(3.6,2.8),A3,A4;
42 A3 = A1 + A2;//A3 = operator+(A1,A2); //对运算符重载函数的调用,前面的为隐式调用,后面的为显示调用
43 A4 = A1 - A2;//A4 = operator-(A1-A2);
44 A1.print();
45 A2.print();
46 A3.print();
47 A4.print();
48
49 return 0;
50 }
复制代码
运行结果如下
2.3+4.6i
3.6+2.8i
5.9+7.4i
-1.3+1.8i
Program ended with exit code: 0`
可重载运算符
不可重载运算符