c++学习小结(10.28 引用和函数重载和函数默认参数)

引用:

int a = 10;
int &b = a;
cout << a << endl; //10
cout << b << endl; //10

引用时必须先初始化 不能 int &b;

利用引用实现数据交换

void swapMy(int &a,int &b)

{        

        int temp = a;

        a = b;

        b = temp;

}

swapMy(a,b);

如果函数的返回值是引用,这个函数的调用可以作为左值。

int &test02()
{
    static int a = 10;
    return a;
}


int main()
{

    int &ref2 = test02();
    test02() = 1000;
    cout << a << ref2; //1000
}

引用的本质是一个指针常量

int &ref = a; // int *const ref = &a;

ref = 20; //*ref = 20;

常量引用

用来修饰形参 防止误操作

int &ref = 10;  //error

const int &ref = 10; //right
//加上const之后 编译器自动把代码转换为 int temp = 10; int &ref = temp;
void printf(const int &value) //用const修饰形参防止函数内误操作修改了a的值
{
    cout << value << endl;
}
int main()
{
    int a = 10;
    printf(a);
}

函数默认参数

int getsum(int a,int b = 20,int c = 30)
{
    return a+b+c;
}

int main()
{
    int sum = getsum(10);
    cout << sum << endl;  //60

}

注意事项:如果某个位置已经有了默认参数,那么从这个位置往后从左到右都必须有默认参数

                  如果函数声明有默认参数,函数实现就不能有默认参数

函数占位参数(本阶段用处不大)

void Print(int a,int)
{
    cout << a << endl;
}

int main()
{
    Print(10,10);
}

占位参数也可以有默认参数。

函数重载

void func()
{
    cout << "123" << endl;
}

void func(int a)
{
    cout << "123" << endl;
}

int main()
{
    func(); //调用第一个函数
    func(10); //调用第二个函数
}

作用:函数名可以相同,提高复用性

函数重载条件:

1.同一个作用域下

2.函数名称相同

3.函数参数类型不同 或个数不同 或顺序不同

注意:函数的返回值不可以作为函数重载的条件

函数重载的注意事项

引用作为函数重载的条件

void func(int &a)
{
    cout << 123 << endl;
}

void func(const int &a)
{
    cout << 123 << endl;
}
//这种写法正确 两个函数的参数类型不同
int main()
{
    int a = 10;
    func(a); //会调用第一个函数 因为a默认为可读可写的变量
    func(10); //会调用第二个函数 因为int &a = 10不合法
}

函数重载碰到默认参数

void func(int a,int b = 10)
{
    cout << 132 << endl;

void func(int a)
{
    cout << 132 << endl;
}


int main()
{
    func(10);//无法执行,两个函数虽然参数个数不同但是都可以调用,这种写法不正确,尽量避免
    func(10,20);//执行第一个函数
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值