-
函數重載回顧
-
函數重載的本質為 相互獨立的不同函數
-
C++中通過 函數名和 函數參數確定函數調用
-
無法直接通過函數名得到重載函數的入口地址
-
函數重載必然發生在 同一個作用域
-
類中的成員函數可以進行重載
-
構造函數的重載
-
普通成員函數的重載
-
靜態成員函數的重載
-
問題:全局函數,普通成員函數以及靜態成員函數之間是否可以構成重載?
-
重載函數的本質為多個不同的函數
-
函數名和參數列表是唯一的標識
-
函數重載必須發生在同一個作用域中
在類中,
普通成員函數以及靜態成員函數之間可以構成重載關系,但是全局函數與類中的成員函數不能構成重載關系,因為
全局函數位於全局的命名空間,而成員函數位於類中,它們之間的作用域已經不一樣了。
#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()
-
函數重載有什么意義?
-
通過函數名對函數功能進行演示
-
通過參數列表對函數用法進行提示
-
擴展系統中已經存在的函數功能
#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:~ $