1. 引用作为函数形参
#include <iostream>
using namespace std;
// 标注1.....无法交换内容
//void Jiaohuan(int a, int b){
// int t=a, a=b, b=t;}
// 标注2.....可以交换内容,标准C写法
//void Jiaohuan(int* a, int* b){
// int t=*a; *a=*b; *b=t;}
// 标注3.....可以交换内容,标准C++写法
void Jiaohuan(int& a, int& b){
int t=a; a=b; b=t;}
//限制改变a对应实参的值,同时输出16进制
void Jiaohuan(const int& a, int& b){
// cout << hex << showbase << a << "\tasd" << endl;
}
int main(){
int m=10, n=20;
// 标注1.....
//Jiaohuan(m, n);
// 标注2.....
//Jiaohuan(&m, &n);
// 标注3.....
Jiaohuan(m, n);
cout << m << " " << n << endl;
//联系函数指针
void(*p)(int&, int&) = &Jiaohuan;
//限制改变a对应实参的值,同时输出16进制
const int aaa = 1212;
int bbb = 2525;
Jiaohuan(aaa, bbb);
getchar();
return 0;
}
2. 引用作为函数返回值
#include <iostream>
using namespace std;
//函数返回值的引用
int& max(int& x, int& y){
return x>y?x:y;
}
int& count(){
static int n = 0;
n++;
return n;
}
int main(){
int m = 10, n = 20;
max(m, n) += 80;
cout << m << " " << n << endl;
count() = 1000;
cout << count() << endl;
cout << count() << endl;
cout << count() << endl;
getchar();
return 0;
}
3. 函数重载(函数重载其实在内部是不同名的)
4. 函数形参默认值
- 形参默认值只能靠右
- 声明和定义分开是,默认值只能在声明中指定
#include <iostream>
using namespace std;
void print(int a[], int n, char sep = ' ', bool bra = true);
void print(int a[], int n, char sep, bool bra){
if (bra) cout << '[';
if (n>0) cout << *a;
for(int i=0; i<n; i++)
cout << sep << a[i];
if (bra) cout << ']';
cout << endl;
}
int main(){
int a[5] = {1,2,3,4,5};
print(a, 5);
getchar();
return 0;
}