函數參數引用傳遞,可以實現雙向傳遞
# include<iostream>
using namespace std;
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x, y;
cin >> x>>y;
swap(x, y);
cout << x << y;
return 0;
}
內聯函數:節省了參數傳遞,控制轉移開銷,內聯函數體內不能有循環語句和switch,內聯函數定義必須在第一次調用之前,對內聯函數不能進行異常接口說明
# include<iostream>
using namespace std;
const double PI = 3.1415927;
inline double calArea(double radius) {
return PI * radius * radius;
};
int main() {
double x;
cin >> x;
double area = calArea(x);
cout <<area ;
return 0;
}
函數重載:函數名一樣,以傳入形參個數或數據類型進行區分,不與輸出類型區分
# include<iostream>
using namespace std;
int add(int x, int y) {
return x + y;
};
int add(int x, int y, int z) {
return x + y + z;
}
int main() {
int x,y,z;
cin >> x>>y>>z;
cout << add(x , y) << endl;
cout << add(x, y, z) << endl;
return 0;
}
函數默認參數
如果有原型申明在定義之前,則默認參數在原型聲明中給出;
有默認參數的形參必須在函數列表最右;
調用時實參與形參的結合次序是從左到右
# include<iostream>
#include<iomanip>
using namespace std;
int getVolume(int length, int width = 2, int height = 9);
int main() {
int x,y,z;
cin >> x>>y>>z;
cout << getVolume(x) << endl;
cout << getVolume(x, y) << endl;
cout << getVolume(x, y, z) << endl;
return 0;
}
int getVolume(int length, int width , int height ) {
cout << "length" << setw(5) << length << setw(5) << "width" << setw(5) << width << setw(5) << "height" << setw(5) << height << endl;
return length * width * height;
}