本文主要讲解的是缺省参数,函数重载,引用的使用.
目录
前言
一、缺省参数是什么?
1.缺省参数的分类
二、函数重载是什么?
三、引用是什么?
1.引用特性
总结
提示:以下是本篇文章正文内容,下面案例可供参考
缺省函数是在声明或定义的时候指定参数缺少指定的一个值。
代码如下(示例):
#include
using namespace std;
void f()
{cout << "f()" << endl;}
void f(int a)
{cout << "f(int a)" << endl;
}
int main()
{int a = 0;f();f(a);return 0;
}
结果如下:
1.全缺省参数
#include
using namespace std;
void f(int a=10,int b=20,int c=30)
{cout << a+b+c << endl;
}int main()
{int x = 0;int y = 0;int z = 10;f();return 0;
}
结果如下:
2.半缺省参数
#include
using namespace std;void f(int x,int y=10,int z=10)
{cout << x+y+z << endl;
}
int main()
{int x = 0;int y = 0;int z = 10;f(x);return 0;
}
结果如下 :
注意:
- 半缺省必须从右到左的给出来
- 缺省参数不能在函数声明和定义同时出现
- 缺省值必须为局部或全局
在同一个作用域中可以同时存在相同的函数名,但这些的相同函数名的形参列表不同(如:参数个数不同,类型不同,类型顺序不同).
代码如下(示例):
void f(int a, int b, int c)
{cout << a << endl;cout << b << endl;cout << c << endl;
}
void f(double a = 11.1, int b = 10, int c = 120)
{cout << a << endl;cout << b << endl;cout << c << endl;
}
int main()
{int x = 0;int y = 0;int z = 10;f(x,y,z);f();return 0;
}
结果:
注意:
1.不用定义含糊不清的形参
void f(int a=10)
{cout << a << endl;
}
void f()
{cout << "hello world" << endl;
}
int main()
{f();f();return 0;
}
引用是再给一个定义好的变量再取一个名,但是他们共用一个内存空间.
使用方法:
类型 & 变量名=引用实体;
- 引用前必须初始化
- 一个变量可以有多个引用
- 引用的名与定义名形同会冲突
int main()
{int x = 0;int& y = x;int& z = y;cout << x << endl;//0y = 10;cout << x << endl;//10z = 20;cout << x << endl;//20return 0;
}
结果:
本文主要讲解的是缺省参数,函数重载,引用的使用.讲的很浅没有深入讲解