C++ 類中的函數重載


我們知道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 = %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 }

注意:

三種函數的本質不同。

普通成員函數和靜態成員函數之間可以構成重載。

普通成員函數和靜態成員函數在同一個作用域(不區分內存類別)中。

類的成員函數和全局函數不能構成重載,不在同一個作用域中。

總結:

1,類的成員函數之間可以進行重載;

    2,重載必須發生在同一個作用域中;

    3,全局函數和成員函數不能構成重載關系;

    4,重載的意義在於擴展已經存在的功能;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM