1,本课程最初阶段就学习了函数重载,但是那时研究目标仅限于全局函数,到目前 为止我们学习了三种函数:
1,全局函数;
2,普通成员函数;
3,静态成员函数;
这三种不同类型的函数之间是否可以构成重载,这是本文讨论的主要内容;
2,函数重载回顾:
1,函数重载的本质为相互独立的不同函数;
2,C++ 中通过函数名和函数参数确定参数调用;
3,无法直接通过函数名得到重载函数的入口地址;
1,如果函数被重载,还需要函数的参数信息;
4,函数重载必然发生在同一个作用域中;
3,类中的重载:
1,类中的成员函数可以进行重载:
1,构造函数的重载;
2,普通成员函数的重载;
3,静态成员函数的重载;
2,全局函数、普通成员函数以及静态成员函数之间是否可以构成重载?
4,万变不离其宗:
1,重载函数本质为多个不同的函数;
1,上述三种函数本质不同;
2,函数名和参数列表是唯一的标识;
1,普通成员函数和静态成员函数之间可以构成重载;
3,函数重载必须发生在同一个作用域中;
1,普通成员函数和静态成员函数在同一个作用域(不区分内存类别)中;
2,类的成员函数和全局函数不能构成重载,不在同一个作用域中;
5,类与重载全面分析实例分析:
1,main.cpp 文件:
1 #include <stdio.h> 2 3 class Test 4 { 5 int i; 6 public: 7 Test() 8 { 9 printf("Test::Test()\n"); 10 this->i = 0; 11 } 12 13 Test(int i) 14 { 15 printf("Test::Test(int i)\n"); 16 this->i = i; 17 } 18 19 Test(const Test& obj) // 三个构造函数之间也构成了重载,这是拷贝构造函数; 20 { 21 printf("Test(const Test& obj)\n"); 22 this->i = obj.i; 23 } 24 25 static void func() 26 { 27 printf("void Test::func()\n"); 28 } 29 30 void func(int i) // 和上面的静态成员函数构成重载; 31 { 32 printf("void Test::func(int i), i = %d\n", i); 33 } 34 35 int getI() 36 { 37 return i; 38 } 39 }; 40 41 void func() 42 { 43 printf("void func()\n"); 44 } 45 46 void func(int i) 47 { 48 printf("void func(int i), i = %d\n", i); 49 } 50 51 int main() 52 { 53 func(); 54 func(1); 55 56 Test t; // Test::Test(); 57 Test t1(1); // Test::Test(int i); 58 Test t2(t1); // Test(const Test& obj); 59 60 func(); // void func(); 61 Test::func(); // void Test::func(); 62 63 func(2); // void func(int i), i = 2; 64 t1.func(2); // void Test::func(int i), i = 2; 65 t1.func(); // void Test::func(); 66 67 return 0; 68 }
2,输出结果:
1 void func() 2 void func(int i), i = 1 3 Test::Test() 4 Test::Test(int i) 5 Test(const Test& obj) 6 void func() 7 void Test::func() 8 void func(int i), i = 2 9 void Test::func(int i), i = 2 10 void Test::func()
6,重载的深度意义:
1,通过函数名对函数功能进行提示;
1,最大的好处;
2,通过参数列表对函数用法进行提示;
1,真正的意义;
2,代码自注释;
3,扩展系统中已经存在的函数功能;
1,更高层次的看待函数重载,虽然实质是增加了新的函数;
7,重载的意义分析编程实验:
1,main.cpp 文件:
1 #include <stdio.h> 2 #include <string.h> 3 4 /* 扩展 strcpy() 函数的功能 */ 5 char* strcpy(char* buf, const char* str, unsigned int n) 6 { 7 return strncpy(buf, str, n); 8 } 9 10 int m