C++ 允许在同一作用域中的某个函数和运算符指定多个定义,分别称为函数重载和运算符重载

函数重载

重载声明是指一个与之前已经在该作用域内声明过的函数或方法具有相同名称的声明,但是它们的参数列表和定义(实现)不相同
当您调用一个重载函数或重载运算符时,编译器通过把您所使用的参数类型与定义中的参数类型进行比较,决定选用最合适的定义。选择最合适的重载函数或重载运算符的过程,称为重载决策

注意重载是面向对象的特性,只有类里才可以重载

插入小提示:c++中print不是关键字

void print(char* c) {
cout << "Printing character: " << c << endl;
}
注意这个函数定义,通过(char * c) 参数接收一个字符串参数,而不是string c


运算符重载

您可以重定义或重载大部分 C++ 内置的运算符。这样,您就能使用自定义类型的运算符。
重载的运算符是带有特殊名称的函数,函数名是由关键字 operator 和其后要重载的运算符符号构成的。与其他函数一样,重载运算符有一个返回类型和一个参数列表。
即声明运算符具有函数的功能
语法返回值 operator?(参数); ?为要重载的运算符

例如Box operator+(const Box&);
注意看参数列表也可以使用关键字如const定义参数
注意这种定义对象接收参数的方法

  1. #include <iostream>
  2. using namespace std;
  3. class Box
  4. { //长宽高为3个私有数据成员,定义相应的公有方法用于访问私有成员
  5. public:
  6. //获得体积函数
  7. double getVolume(void)
  8. {
  9. return length * breadth * height;
  10. }
  11. void setLength( double len ) //设置长
  12. {
  13. length = len;
  14. }
  15. void setBreadth( double bre ) //设置宽
  16. {
  17. breadth = bre;
  18. }
  19. void setHeight( double hei ) //设置高
  20. {
  21. height = hei;
  22. }
  23. // 重载 + 运算符,用于把两个 Box 对象相加
  24. Box operator+(const Box& b)
  25. {
  26. Box box; //定义一个对象用于接收2个box对象相加的结果,然后返回
  27. box.length = this->length + b.length;
  28. box.breadth = this->breadth + b.breadth;
  29. box.height = this->height + b.height;
  30. return box;
  31. }
  32. private:
  33. double length; // 长度
  34. double breadth; // 宽度
  35. double height; // 高度
  36. };
  37. // 程序的主函数
  38. int main( )
  39. {
  40. Box Box1; // 声明 Box1,类型为 Box
  41. Box Box2; // 声明 Box2,类型为 Box
  42. Box Box3; // 声明 Box3,类型为 Box
  43. double volume = 0.0; // 把获得体积函数的结果存储在该变量中
  44. // Box1 详述
  45. Box1.setLength(6.0);
  46. Box1.setBreadth(7.0);
  47. Box1.setHeight(5.0);
  48. // Box2 详述
  49. Box2.setLength(12.0);
  50. Box2.setBreadth(13.0);
  51. Box2.setHeight(10.0);
  52. // Box1 的体积
  53. volume = Box1.getVolume();
  54. cout << "Volume of Box1 : " << volume <<endl;
  55. // Box2 的体积
  56. volume = Box2.getVolume();
  57. cout << "Volume of Box2 : " << volume <<endl;
  58. // 把两个对象相加,得到 Box3
  59. Box3 = Box1 + Box2;
  60. // Box3 的体积
  61. volume = Box3.getVolume();
  62. cout << "Volume of Box3 : " << volume <<endl;
  63. return 0;
  64. }
  65. 当上面的代码被编译和执行时,它会产生下列结果:
  66. Volume of Box1 : 210
  67. Volume of Box2 : 1560
  68. Volume of Box3 : 5400

Box operator+(const Box& b)
{
Box box; //定义一个对象用于接收2个box对象相加的结果,然后返回
box.length = this->length + b.length;

Box3 = Box1 + Box2;
注意看这2步,box1+box2中,box1为调用重载运算符(重载运算符是特殊的函数,定义在类里自然相当于成员函数,具有this指针),box2就为重载运算符函数的参数

重载运算符函数体就相当于box.length = Box1.length + Box2.length;

下面是可重载的运算符列表:

+ - * / % ^
& | ~ ! , =
< > <= >= ++
<< >> == != && ||
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
-> ->* new new [] delete delete []

下面是不可重载的运算符列表:

:: .* . ?:

更多重载运算符的实例

下面提供了各种运算符重载的实例,帮助您更好地理解重载的概念。

序号 运算符和实例
1 一元运算符重载
2 二元运算符重载
3 关系运算符重载
4 输入/输出运算符重载
5 ++ 和 — 运算符重载
6 赋值运算符重载
7 函数调用运算符 () 重载
8 下标运算符 [] 重载
9 类成员访问运算符 -> 重载