C++学习笔记 (17)—— 函数提高

1.1、函数默认参数

在c++中,函数的参数列表中的形参是可以有默认值

语法:

  • 返回类型 函数名  (参数=默认值){}

 注意:

  • 如果某个位置上已经有了默认参数,那么从这个位置开始往后,从左到右都必须有默认参数
  • 如果函数声明中有了默认参数,函数实现中就不能再有默认参数

eg:

#include <iostream>
using namespace std;
//定义一个函数,答应参数的值
void prit(int a = 0, int b = 91);
int main()
{

cout << "函数默认参数:" << endl << endl;
//注意事项:
//1.如果某个位置上已经有了默认参数,那么从这个位置开始往后,从左到右都必须有默认参数
//2.如果函数声明中有了默认参数,函数实现中就不能再有默认参数

//函数调用 ,使用默认参数
prit();
cout << "--------------" << endl;
//函数调用,使用传入的参数、
prit(12, 67);
system("pause");
return 0;
}
void prit(int a , int b )
{

cout << "a =" << a << endl;
cout << "b =" << b << endl;

}

 

1.2、函数占位符

c++中函数的形参列表里可以有展位参数,用来做占位,调用函数时必须填补该位置

语法:

  • 返回值类型 函数名 (数据类型){}

现阶段函数的展位参数意义不大,但是后面的会用到该技术

 分为:

  • 有参数的占位符
  • 无参数的占位符

 

eg:

#include <iostream>

using namespace std;
//1.没有默认参数的占位符
void prrt(int a, int)
{
cout << "没有默认参数的占位符:" << endl<<endl;
}
//2.有默认参数的占位符
void prrt1(int a = 0, int = 0)
{
cout << "有默认参数的占位符:" << endl << endl;

}
int main()
{
cout << "函数占位符:" << endl<<endl;
//函数调用
prrt(10, 11);
//调用函数
prrt1();
system("pause");
return 0;
}

1.3、函数重载

作用:

  • 函数名可以相同,提高服用性

函数重载满足条件:

  • 同一个作用域下
  • 函数名相同
  • 函数参数不同、类型不同、参数个数不同、参数顺序不同

注意:

  • 函数的返回值不可作为函数重载的条件

eg:

#include <iostream>
using namespace std;
//1.参数类型不同
void test(int)
{
cout << "我是重载函数001" << endl;
}
void test(double)
{
cout << "我是重载函数002" << endl;
}
//2.参数数目不同
void test(int, int)
{
cout << "我是重载函数003" << endl;
}
//3.参数顺序不同
void test(double, int)
{
cout << "我是重载函数004" << endl;
}
int main()
{
cout << "函数重载:" << endl<<endl;
//函数调用
test(10);
test(3.14);
test(10,2);
test(3.14,10);

system("pause");
return 0;
}

1.4、函数重载注意事项

  • 引用作为函数重载条件
  • 函数重载碰到函数默认参数

eg:

#include <iostream>
using namespace std;
//函数重载的注意事项
//1.引用作为重载的条件
void fun(int& a) //int &a =10; 不合法
{
cout << "func(int& a)调用" << endl << endl;
}
void fun(const int& a) //const int& a =10;合法的,加const后编译器坐了优化,相当于创建了一个临时的数据,指向这个地址
{
cout << "func(const int& a)调用" << endl << endl;
}
//2.函数重载碰到默认参数
void fun(int a, int b )
{

}
void fun(int a,int b,int = 10)
{

}
int main()
{
cout << "函数重载注意时事项:" << endl << endl;
int a = 0;
fun(a);
fun(10);
fun(10, 10); //两个带默认参数的函数都能调用,出现二义性
system("pause");
return 0;
}

posted @ 2022-04-16 17:36  雾枫  阅读(32)  评论(0编辑  收藏  举报