C++的使用小教程5——类的重载

悠悠 2024-04-18 23:00 50阅读 0赞

C++的使用小教程5——类的重载

  • 1、类的重载是什么
  • 2、函数的重载
  • 3、运算符的重载

学习好幸苦。
在这里插入图片描述

1、类的重载是什么

C++的重载分为两类,一个是函数的重载,一个是运算符的重载,重载的意思就是允许在一个作用域内对函数或者运算符指定多个定义,以实现不同的功能。
其中函数的重载是,在同一个作用域内,可以声明与定义几个名字相同的函数,但是其形式参数不同(不同包括形式参数类型、多少、顺序等等),但是必须注意的是不能仅通过返回类型的不同来重载函数。
其中运算符的重载是,这里用一个例子来说明,**假设我们定义了一个int a = 5,int b = 10;此时调用int c = a + b;得到c = 15。**但是对于我们自己定义的class而言,比如class Box,那么box3 = box1 + box2;是什么意思呢?这就是运算符的重载需要定义的。

2、函数的重载

在同一个作用域内,可以声明与定义几个名字相同的函数,但是其形式参数不同(不同包括形式参数类型、多少、顺序等等),但是必须注意的是不能仅通过返回类型的不同来重载函数。
在接下来的举例中,我将通过打印字符串实现函数的重载。

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. class printExample
  5. {
  6. public:
  7. void print(int i) {
  8. cout << "此时输出为整型:" << i << endl;
  9. }
  10. void print(double d) {
  11. cout << "此时输出为浮点型:" << d << endl;
  12. }
  13. void print(string s) {
  14. cout << "此时输出为字符串: " << s << endl;
  15. }
  16. };
  17. int main(void)
  18. {
  19. printExample test;
  20. // 此时输出为整型
  21. test.print(5);
  22. // 此时输出为浮点型
  23. test.print(500.263);
  24. // 此时输出为字符串
  25. test.print("OK");
  26. system("pause");
  27. return 0;
  28. }

输出结果为:

  1. 此时输出为整型:5
  2. 此时输出为浮点型:500.263
  3. 此时输出为字符串: OK
  4. 请按任意键继续. . .

3、运算符的重载

我们可以重载C++中大部分的运算符,其重载的格式为:

  1. Box operator+(const Box&);

如上的声明重载的是加法运算符,其作用是把两个 Box 对象相加,返回最终的 Box 对象。在应用时,调用如下函数。

  1. box3 = box2 + box1;

当然,返回对象和重载的运算符都可以修改,只要修改重载格式中的”Box”和”+”即可。
在接下来的例子中,我将通过重载运算符实现两个box的相加,相加的内容是两个box的length和width。

  1. #include <iostream>
  2. #include <cstring>
  3. using namespace std;
  4. /*Box基类*/
  5. class Box
  6. {
  7. protected:
  8. int width;
  9. int length;
  10. public:
  11. void setWidth(int widthIn);
  12. void setLength(int lengthIn);
  13. int getWidth();
  14. int getLength();
  15. // 声明运算符重载函数
  16. Box operator+(const Box& b);
  17. };
  18. void Box::setWidth(int widthIn){
  19. width = widthIn;
  20. }
  21. void Box::setLength(int lengthIn) {
  22. length = lengthIn;
  23. }
  24. int Box::getWidth() {
  25. return width;
  26. }
  27. int Box::getLength() {
  28. return length;
  29. }
  30. // 定义运算符重载函数
  31. Box Box::operator+(const Box& b)
  32. {
  33. Box box;
  34. box.width = this->width + b.width;
  35. box.length = this->length + b.length;
  36. return box;
  37. }
  38. int main()
  39. {
  40. Box smallbox;
  41. Box box;
  42. Box bigbox;
  43. smallbox.setLength(5);
  44. smallbox.setWidth(5);
  45. box.setLength(10);
  46. box.setWidth(10);
  47. bigbox = smallbox + box;
  48. cout << "The length of the small box is " << smallbox.getLength() << endl;
  49. cout << "The length of the box is " << box.getLength() << endl;
  50. cout << "The length of the big box is " << bigbox.getLength() << endl;
  51. system("pause");
  52. }

输出结果为:

  1. The length of the small box is 5
  2. The length of the box is 10
  3. The length of the big box is 15

发表评论

表情:
评论列表 (有 0 条评论,50人围观)

还没有评论,来说两句吧...

相关阅读