引用
引用就是一个变量或者是常量的别名
数据类型 &引用名称 = 引用对象 (引用类型必须与引用对象一致)
例子:
#include<iostream>
using namespace std;
int main(void)
{
int a=10;
int &ra = a; //ra就是a的引用
cout<<&a<<" "<<a<<endl;
cout<<&ra<<" "<<ra<<endl;
}
0x7ffc0d9f3e7c 10
0x7ffc0d9f3e7c 10
特点:
- 引用定义的时候必须要初始化(引用必须要引用对象-形参除外)
- 引用类型必须与引用对象一致
- 引用只能引用一个对象, 一个对象可以被次引用
- int a=10; int &ra = a; int &rb = a; int &rc =ra
- ”引用本身不占用内存空间与引用对象共用空间“
- 不能创建数组的引用
- 如果引用的对象是常量,那么引用必须用const修饰
- const int a=10; const int &ra = a;
- const int &a = 10;
引用作为函数参数
函数传参方式:传值, 传地址, 传引用
格式:
函数返回值类型 函数名称(数据类型 &变量, ...){}
例子:
传值--不能实现交换
void swap(int a, int b)
{
int t = a;
a= b;
b=t;
}
传地址-指针 (可以交换)
void swap(int *a, int *b)
{
int t = *a;
*a= *b;
*b=t;
}
传引用--可以交换
void swap(int &a, int &b)
{
int t = a;
a= b;
b=t;
}
int a=10,b=20
swap(a, b);
引用作为函数参数有时候要避免在函数内部通过引用修改对象本身
比如:
int add (const int &a , const int &b)
{
a++; //这样会修改函数实参
return a+b;
}
int c = add(10,20);
int d =add(a,b);
函数返回引用
必须满足:函数调用完后返回值必须存在
int &fun()
{
static int a=10;
return a;
}
int &b = fun();
函数的返回值是引用,可以把函数调用作为赋值运算符的左值
fun()=100; ===》 把100赋值给了fun()函数的返回值, 返回值引用static int a, 所以100其实是赋值给到a
******************************************************************************************************
函数重载
同一作用域里面同名函数,参数列表不同,这样的两个或多个函数称为函数重载
函数重载判断依据:
- 函数名必须相同
- 函数参数列表不同(个数, 类型),const修饰看作类型不同
- 函数返回值不能作为函数重载判断依据
void fun(const int x) void fun(int x)不允许同时出现
void fun(const int* x) void fun(int* x) 属于重载
void fun(const int& x) void fun(int &x) 属于重载
作用:
- 解决函数名字资源问题
- 函数调用的时候使用方便,自动根据不同的参数调用不同函数(静态多态-编译时候多态)
在c++中检查函数名称和参数列表, 在c语言中只检查函数名称
*****************************************
函数默认参数(缺省参数)
设置函数的时候大多数情况下是固定, 只有极少数时候需要改变,那就可以把固定的参数设置为默认参数
比如:
int hopen(const char *path, int flag = O_RDWR);
调用:
int fd = hopen(“./my.txt”);
int fd = hopen(“./my.txt”, O_RDONLY);
默认参数需要注意:
- 如果多参数默认,必须满足从右往左连续默认
- void fun(int a, int b=9, int c=1); 允许
- void fun(int a=1, int b, int c=2); 不允许
- 如果函数声明和实现分开, 那么默认参数要写在声明部分, 不能写在实现部分
- void fun(int a, int b, int c=1); 声明
- void fun(int a, int b, int c){} 实现
int data
void fun(int &a=1)
*******************************************************************
例子:设计一个录入学生信息的函数(参数为学生信息)(输入信息有个学号,姓名,年龄,班级 参数顺序自定),结合函数重载和默认参数的特点。
struct Student{
char name[32];
char clss[32];
int number;
int age;
}
struct Student * inputInfo(const char *name=”zs”, int number=0, int age=20, const char *clss=”1816000”)
{
struct Student *stu = new struct Student;
strcpy(stu->name , name);
strcpy(stu->clss, clss);
stu->number = number;
stu->age = age;
return stu;
}
//以下函数重载,参考上面函数重载判断依据
struct Student *a = inputInfo();
struct Student *a = inputInfo(“lisi”);
struct Student *a = inputInfo(“lisi”, 110);
struct Student *a = inputInfo(“lisi”, 110, 21);
struct Student *a = inputInfo(“lisi”, 110, 20, “1816000”);