C++核心編程——函數提升
一、函數默認參數
- 在C++中,函數的形參列表中的形參是可以有默認值的
- 語法:
返回值類型 函數名 (參數=默認值){}
示例
#include<iostream>
using namespace std;
int t4func2(int a, int b = 10, int c = 20) {
return a + b + c;
}
int main() {
cout << t4func2(10) << endl; //40
cout << t4func2(10, 10, 20) << endl; //40
system("pause");
return 0;
}
注意:
- 在函數參數列表中某個位置已經有了默認參數,那麼從這個參數開始往後的參數必須有默認值
- 如果函數聲明中有默認參數,函數實現就不能有默認參數
二、函數佔位參數
- C++中函數的形參列表裏可以有佔位參數,用來佔位,調用函數時必須填補此位置
- 語法:
返回值類型 函數名(數據類型){}
#include<iostream>
using namespace std;
void t4func3(int a, int) {
cout << "a = " << a << endl;
}
int main() {
t4func3(1, 1);
system("pause");
return 0;
}
三、函數重載
3.1函數重載描述
**作用:**函數名可以相同,提高複用性
函數重載滿足條件
- 同一作用域下
- 函數名稱相同
- 函數參數類型不同 或者個數不同 或者順序不同
注意:
- 函數的返回值不可以作爲函數重載的條件
- 函數重載需要函數都在同一作用域下
示例:
#include<iostream>
using namespace std;
void t5func1(int a) {
cout << "a = " << a << endl;
}
void t5func1(int a, int b) {
cout << "a = " << a << " b = " << b << endl;
}
int main() {
t5func1(1);
t5func1(1, 1);
/*
a = 1
a = 1 b = 1
*/
system("pause");
return 0;
}
3.2函數重載注意事項
- 引用作爲重載條件
#include<iostream>
using namespace std;
void t5func2(int& a) {
cout << "t5func2(int& a) = " << a << endl;
}
void t5func2(const int& a) {
cout << "t5func2(const int& a) = " << a << endl;
}
int main() {
int a = 10;
t5func2(a); // t5func2(int& a) = 10
t5func2(1); // t5func2(const int& a) = 1
system("pause");
return 0;
}
- 函數重載碰到函數默認參數
- 當遇到這種情況時會出現二義性,編譯器會報錯