默认参数函数,引用

一:默认参数函数

#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void test(int sum = 0) //函数的定义 
{
    cout<<"默认参数sum="<<sum<<endl;
}
void test1(int c = 0) 
{
    cout<<"默认参数c="<<c<<endl;
}
void test2(int x = 0,int y = 1,int b = 0)
{
    cout<<"使用默认参数时要从右至左逐次定义"<<endl;
}
//void test3(int x = 1,int y,int b = 0) //未从右至左逐次定义 中间有一个没有使用默认参数 
void test4(int x,float y = 0,int b = 0)
{
    cout<<"从右至左逐次定义"<<endl;
}
int main(int argc, char** argv) 
{

    void test1(int c = 0); 
    test1();
    test(); 
    test2();
    test4(4); //在调用函数时,传入的参数是从左至右匹配的,其中未指定默认值的参数必须传入实际值。 
    return 0;
}

二:引用基本概念:

(1):语法格式:类型标识符&引用名=目标变量名。

(2):类型标识符是指目标变量的类型。

(3):声明引用时,必须同时对其进行初始化,即给出引用的具体变量。

(4): 声明引用完毕后,相当于目标变量有两个名称,即该目标原名称和引用名。

(5):声明一个引用不是新定义了一个变量,它只表示该引用名是目标变量名的一个别名,所以,系统并不给引用分配存储单元.

 1 #include <iostream>
 2 using namespace std;
 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 4 void test(int &r)
 5 {
 6     cout<<"通过修改引用作为参数的形参可以修改到实参"<<endl;
 7     r = 10;
 8  } 
 9  
10 int main(int argc, char** argv) 
11 {
12     int f = 8;
13     int &r = f; //引用一个变量 
14     cout<<"r="<<"f="<<r<<"="<<f<<endl;
15     
16     r = 2; //记住引用是不具备内存空间的,so此时修改的是f;
17     cout<<f<<endl; //2
18      
19     int c = 0;
20     r = c;
21     cout<<"引用c后的r="<<r<<"f="<<f<<endl; //输出:引用c后的r=0f=0。
22     /*【注意】:不管你怎么使用记住他只是被引用的变量的一个别名,他什么都没有,但是通过他可以间接的来修改他所引用的变量, 
23     不能与指针的定义混淆. 
24     */ 
25     
26 //引用作为函数的参数.
27      int s = 100;
28      test(s);
29      cout<<"修改引用形参来修改被引用的实参s"<<s<<endl;//s = 10;
30  
31     return 0;
32 }

三:用指针来做形式参数。

 1 #include <iostream>
 2 using namespace std;
 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 4 
 5 int test(int *p) //p是指向实参的指针变量,是具备内存空间的。 
 6  {
 7      *p = 10;
 8      return 0;
 9   } 
10 
11 int test1(int (*c)[10] )
12 {
13     cout<<*c<<endl;
14 }
15 int main(int argc, char** argv) 
16 {
17     int f = 100;
18     cout<<"输出实参未改变前的地址。判断修改前和修改后地址是否相同,"<<&f<<endl; //输出实参未改变前的地址。判断修改前和修改后地址是否相同,0x6ffe1c
19     test(&f); //传入的是f的地址 
20     cout<<f<<endl; //10
21     cout<<"输出改变值后的地址"<<&f<<endl; //输出改变值后的地址0x6ffe1c
22 
23 
24 //我们知道函数是不能返回数组的,所以我们通过指针来实现返回数组
25      int s[10] = {1,2,3,4,5,6,7,8,9,10};
26      int *c = test1(&s);
27      cout<<*c<<endl;
28     return 0;
29 }

 

posted @ 2020-02-29 22:59  calm寻路人  阅读(412)  评论(0编辑  收藏  举报