函数提高
函數(shù)默認(rèn)參數(shù)
#include <iostream> using namespace std;int func(int a, int b = 10, int c = 10) {return a + b + c; }//1. 如果某個(gè)位置參數(shù)有默認(rèn)值,那么從這個(gè)位置往后,從左向右,必須都要有默認(rèn)值 //2. 如果函數(shù)聲明有默認(rèn)值,函數(shù)實(shí)現(xiàn)的時(shí)候就不能有默認(rèn)參數(shù) int func2(int a = 10, int b = 10); int func2(int a, int b) {return a + b; }int main() {cout << "ret = " << func(20, 20) << endl;cout << "ret = " << func(100) << endl;system("pause");return 0; }函數(shù)占位參數(shù)
C++中函數(shù)的形參列表里可以有占位參數(shù),用來做占位,調(diào)用函數(shù)時(shí)必須填補(bǔ)該位置
#include <iostream> using namespace std; //函數(shù)占位參數(shù) ,占位參數(shù)也可以有默認(rèn)參數(shù) void func(int a, int) {cout << "this is func" << endl; }int main() {func(10,10); //占位參數(shù)必須填補(bǔ)system("pause");return 0; }函數(shù)重載
函數(shù)重載概述
作用:函數(shù)名可以相同,提高復(fù)用性
函數(shù)重載滿足條件:
-
同一個(gè)作用域下
-
函數(shù)名稱相同
-
函數(shù)參數(shù)類型不同 或者 個(gè)數(shù)不同 或者 順序不同
注意: 函數(shù)的返回值不可以作為函數(shù)重載的條件
#include <iostream> using namespace std; //函數(shù)重載需要函數(shù)都在同一個(gè)作用域下 void func() {cout << "func 的調(diào)用!" << endl; } void func(int a) {cout << "func (int a) 的調(diào)用!" << endl; } void func(double a) {cout << "func (double a)的調(diào)用!" << endl; } void func(int a ,double b) {cout << "func (int a ,double b) 的調(diào)用!" << endl; } void func(double a ,int b) {cout << "func (double a ,int b)的調(diào)用!" << endl; }//函數(shù)返回值不可以作為函數(shù)重載條件 //int func(double a, int b) //{ // cout << "func (double a ,int b)的調(diào)用!" << endl; //}int main() {func();func(10);func(3.14);func(10,3.14);func(3.14 , 10);system("pause");return 0; }函數(shù)重載注意事項(xiàng)
-
引用作為重載條件
-
函數(shù)重載碰到函數(shù)默認(rèn)參數(shù)
總結(jié)
- 上一篇: 内存分区模型
- 下一篇: 设计立方体类(求出立方体的面积和体积