引用简介
引用的作用就是给变量起别名
语法:数据类型 &别名 = 原名
#include<iostream>
using namespace std;
int main(){
int a = 10;
//创建引用
int &b = a;
cout<<"a = "<<a<<end1;
cout<<"b = "<<b<<end1;
b = 100;
cout<<"a = "<<a<<end1;
cout<<"b = "<<b<<end1;
system("pause");
return 0;
}
b是a的别名
不过引用前必须初始化,若创建b为a的别名,那么b就不能为c的别名,只能做赋值
#include<iostream>
using namespace std;
int main(){
int a = 10;
//创建引用
int &b = a;
int c = 20;
b = c;
cout<<"a = "<<a<<end1;
cout<<"b = "<<b<<end1;
cout<<"c = "<<c<<end1;
system("pause");
return 0;
}
这样a,b,c打印都是20
函数高级运用
默认参数
#include<iostream>
using namespace std;
int func(int a, int b = 10, int c = 20 )
{
return a + b + c;
}
//int b = 10,int c = 20即为默认参数
int main(){
cout<<func(10)<<end1;
cout<<func(10,50,60)<<end1;
system("pause");
return 0;
}
默认参数的意思是,如果你不赋值,则选取默认值,赋值了,采取你新赋的值
占位符
#include<iostream>
using namespace std;
void func(int a, int )
{
cout<<"this is func "<<end1;
}
//int用于占位,需要输入个整型变量
int main(){
cout<<func(10,20)<<end1;
system("pause");
return 0;
}
函数重载
函数重载的函数名可以相同,提高复用性
条件:
1.同一作用域下
2.函数名称相同
3.函数参数类型不同或格式不同或顺序不同
函数返回值的类型相同方可重载
#include<iostream>
using namespace std;
void func()
{
cout<<"this is func "<<end1;
}
void func(int a)
{
cout<<"this is func(int a) "<<end1;
}
int main(){
func(); //调用第一个函数
func(10); //调用第二个函数
system("pause");
return 0;
}
网友评论