C++類中的重載


  • 函數重載回顧
  1. 函數重載的本質為 相互獨立的不同函數
  2. C++中通過 函數名函數參數確定函數調用
  3. 無法直接通過函數名得到重載函數的入口地址
  4. 函數重載必然發生在 同一個作用域
  • 類中的成員函數可以進行重載
  1. 構造函數的重載
  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;
}
運行結果:

pi@raspberrypi:~ $ g++ main.cpp
pi@raspberrypi:~ $ ./a.out
void func()
void func(int i), i = 1
Test::Test()
Test::Test(int i)
Test(const Test& obj)
void func()
void Test::func()
void func(int i), i = 2
void Test::func(int i), i = 2
void Test::func()

 
 
  • 函數重載有什么意義?
  1. 通過函數名對函數功能進行演示
  2. 通過參數列表對函數用法進行提示
  3. 擴展系統中已經存在的函數功能
#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*str = "hello";
    char buf[3] = {0};
    strcpy(buf,str,sizeof(str)-1);
    printf("%s\n",buf);
    return 0;
}
運行結果:

pi@raspberrypi:~ $ g++ main.cpp
pi@raspberrypi:~ $ ./a.out
hel
pi@raspberrypi:~ $

 

 


 
 
 
 
 
 
 
 


免責聲明!

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



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