C++函數重載,重寫,重定義
阿新 • • 發佈:2019-04-04
函數 clu 進行 通過 include 重寫 父類 函數重寫 str
目錄
- 1 重載
- 2 重寫
- 3 重定義
- 4 函數重載二義性
??筆者原創,轉載請註明出處
??C++中經常會提到重載,除了重載,還有重寫,重定義,下面對這三個概念逐一進行區分
1 重載
??函數重載是同一定義域中(即同一個類中)的同名函數,但形參的個數必須不同,包括參數個數,類型和順序,不能僅通過返回值類型的不同來重載函數
#include<iostream> using namespace std; class BOX { void func(int a, int b, int c){} void func(int a, int b){} // 參數個數不同 void func(int c, int b, int a){} // 參數順序不同 int func(int a, int b, int c){} // **返回值類型不同,不能說明是重載函數** }; int main() { BOX box; return 0; }
2 重寫
??在父類和子類中,並且函數形式完全相同,包括返回值,參數個數,類型和順序,
??父類中有vietual
關鍵字,可以發生 多態
#include<iostream> using namespace std; class BOX { virtual void func(int a, int b, int c = 0) // 函數重寫 { } }; class squareBox: public BOX { void func(int a, int b, int c = 0) { } }; int main() { BOX box; return 0; }
3 重定義
??重定義和函數重寫類似,不同的地方是重定義父類中沒有vietual
關鍵字,不可以發生 多態
#include<iostream> using namespace std; class BOX { void func(int a, int b, int c = 0) //**沒有virtual關鍵字,函數重定義** { } }; class squareBox: public BOX { void func(int a, int b, int c = 0) { } }; int main() { BOX box; return 0; }
4 函數重載二義性
??當函數重載遇上默認參數時,會出現二義性
??如下代碼所示:
#include<iostream>
using namespace std;
class BOX
{
void func(int a, int b, int c = 0)
{
}
void func(int a, int b)
{
}
};
int main()
{
BOX box;
box.func(1, 2); // **此函數不知道調用上面哪一個**
return 0;
}
此博文隨著筆者的學習會持續更新
如有錯誤之處,敬請指正,萬分感謝!
C++函數重載,重寫,重定義