c/c++语言开发共享C++ 类中的函数重载

我们知道C++中非常重要的:1.全局函数、2.普通成员函数、3.静态成员函数。 类中的成员函数构成的重载有这几点: 1. 构造函数的重载。 2.普通成员函数的重载。 3.静态成员函数的重载。 例子: 1 #include <stdio.h> 2 3 class Test 4 { 5 int i; 6 …

我们知道c++中非常重要的:1.全局函数、2.普通成员函数、3.静态成员函数。 

类中的成员函数构成的重载有这几点:

  1. 构造函数的重载。

  2.普通成员函数的重载。

  3.静态成员函数的重载。

例子:

 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 = %dn", 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 = %dn", 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 }

注意:

三种函数的本质不同。

普通成员函数和静态成员函数之间可以构成重载。

普通成员函数和静态成员函数在同一个作用域(不区分内存类别)中。

类的成员函数和全局函数不能构成重载,不在同一个作用域中。

总结:

1,类的成员函数之间可以进行重载;

    2,重载必须发生在同一个作用域中;

    3,全局函数和成员函数不能构成重载关系;

    4,重载的意义在于扩展已经存在的功能;

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/600077.html

(0)
上一篇 2021年5月9日
下一篇 2021年5月9日

精彩推荐