[TOC] 1. 函數重載回顧 函數重載的本質為相互獨立的不同函數 C++通過函數名和函數參數確定函數調用 無法直接通過函數名得到重載函數的入口地址 函數重載必然發生在同一個作用域中 2. 類中的函數重載 類的成員函數可以進行重載,包括 構造函數的重載 普通成員函數的重載 靜態成員函數的重載 註意: ...
目錄
1. 函數重載回顧
- 函數重載的本質為相互獨立的不同函數
- C++通過函數名和函數參數確定函數調用
- 無法直接通過函數名得到重載函數的入口地址
- 函數重載必然發生在同一個作用域中
2. 類中的函數重載
類的成員函數可以進行重載,包括
- 構造函數的重載
- 普通成員函數的重載
- 靜態成員函數的重載
註意:函數重載必然發生在同一個作用域中,因此全局函數和類的成員函數無法構成重載。
#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(); // void func()
func(1); // void func(int i), i = 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;
}
重載的意義
- 通過函數名對函數功能進行提示
- 通過參數列表對函數用法進行提示
- 擴展系統中已經存在的函數功能
#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 = "D.T.Software";
char buf[8] = {0};
strcpy(buf, s, sizeof(buf) - 1);
printf("%s\n", buf);
return 0;
}