【C++深度剖析學習總結】 29 類中的函數重載

【C++深度剖析學習總結】 29 類中的函數重載

作者 CodeAllen ,轉載請註明出處


1.函數重載回顧
函數重載的本質爲相互獨立的不同函數

C++中通過函數名和函數參數確定函數調用
無法直接通過函數名得到重載函數的入口地址
函數重載必然發生在同一個作用域中

2.類中的重載
類中的成員函數可以進行重載

  • 構造函數的重載
  • 普通成員函數的重載
  • 靜態成員函數的重載
  • 問題:全局函數,普通成員函數以及靜態成員函數之間是否可以構成重載?

3.萬變不離其宗

  • 1.重載函數的本質爲多個不同的函數
  • 2.函數名和參數列表是唯一的表示
  • 3.函數重載必須發生在同一個作用域中 (類和全局就不行,因爲作用域已經不同了)

實驗:類與重載

#include <stdio.h>

class Test
{
    int i;
public:
    Test()
    {
        printf("Test::Test()\n");
        this->i = 0;
    }
    
    Test(int i)
    {
        printf("Test::Test(int i)\n");
        this->i = i;
    }
    
    Test(const Test& obj)
    {
        printf("Test(const Test& obj)\n");
        this->i = obj.i;
    }
    
    static void func()
    {
        printf("void Test::func()\n");
    }
    
    void func(int i)
    {
        printf("void Test::func(int i), i = %d\n", i);
    }
    
    int getI()
    {
        return i;
    }
};

void func()
{
    printf("void func()\n");
}

void func(int i)
{
    printf("void func(int i), i = %d\n", i);
}

int main()
{
    func();
    func(1);
    
    Test t;        // Test::Test()
    Test t1(1);    // Test::Test(int i)
    Test t2(t1);   // Test(const Test& obj)
    
    func();        // void func()
    Test::func();  // void Test::func()
    
    func(2);       // void func(int i), i = 2;
    t1.func(2);    // void Test::func(int i), i = 2
    t1.func();     // void Test::func()
    
    return 0;
}

4.深度的意義—現在提倡代碼自助式,即不需要註釋來說明如何調用
重載的意義

  • 通過函數名對函數功能進行提示
  • 通過參數列表對函數用法進行提示
  • 擴展系統中已經存在的函數功能

實驗2 重載的意義分析

#include<stdio.h>
#include<string.h>
char* strcpy(char* buf, const char* str, unsigned int n)
{
    return strncpy(buf, str, n);
}
int main()
{
    const char* s = "asdf";
    char buf[3] = {0};
    //strcpy(buf, s);
    //strncpy(buf,s,sizeof(buf)-1); //C語言的做法 ~ what c language do
    strcpy(buf,s,sizeof(buf)-1);
    printf("%s\n", buf);
    return 0;
}

5.思考
重載能夠擴展系統中已經存在的函數功能!那麼重載是否也能夠擴展其他更多的功能?
下面的複數解決方案是否可行?不可行

小結
類的成員函數之間可以進行重載
重載必須發生在同一個作用域中
全局函數和成員函數不能構成重載關係
重載的意義在於擴展已經存在的功能

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章