1 // C++函数和类 27-复习1.cpp: 定义控制台应用程序的入口点。
2 //
3
4 #include "stdafx.h"
5 #include <iostream>
6 #include <string>
7
8 using namespace std;
9
10 //函数原型
11 int max(int num1, int num2);
12 //默认参数
13 int max(int num1 = 5, int num2 = 10);
14 //默认参数
15 void greet(string name = "Student");
16
17 void swap(int &num1, int &num2);
18 //函数重载
19 void swap(int *num1, int *num2);
20
21 long fact(int i);
22 int main()
23 {
24 int num1 = 20;
25 int num2 = 15;
26 //函数调用
27 int res = max(num1, num2);
28 cout << num1 << "和"<< num2 << "中较大的值为:" << res << endl;
29
30 //调用带默认参数的函数
31 int res2 = max();
32 cout << "默认参数函数的结果中较大的值为:" << res2 << endl;
33 greet("uimodel");
34 greet();
35
36 cout << "交换前 num1:" << num1 << "/ num2:" << num2 << endl;
37 swap(num1, num2);
38 cout << "交换后 num1:" << num1 << "/ num2:" << num2 << endl;
39
40 cout << "交换前 num1:" << num1 << "/ num2:" << num2 << endl;
41 swap(&num1, &num2);
42 cout << "交换后 num1:" << num1 << "/ num2:" << num2 << endl;
43
44 cout << "5的阶乘为:" << fact(5) << endl;
45 return 0;
46 }
47
48 //按值传递
49 //函数定义
50 //有返回类型 函数名 (参数列表){函数体}
51 int max(int num1, int num2)
52 {
53 return num1 > num2 ? num1 : num2;
54 }
55
56 //没有返回值的函数
57 void greet(string name)
58 {
59 cout << name << ",Hello!" << endl;
60 }
61
62 //按引用传递
63 void swap(int &num1, int &num2)
64 {
65 int temp = num1;
66 num1 = num2;
67 num2 = temp;
68 cout << "参数类型为引用类型" << endl;
69 }
70 //传递指针类型,函数重载,通过实参类型去判断使用的函数是哪一个
71 void swap(int *num1, int *num2) //
72 {
73 int temp = *num1;
74 *num1 = *num2;
75 *num2 = temp;
76 cout << "参数类型为指针类型" << endl;
77 }
78
79 //递归函数
80 long fact(int i)
81 {
82 long temp;
83 if (i == 0)
84 {
85 temp = 1;
86 }
87 else
88 {
89 temp = i * fact(i - 1);
90 }
91 return temp;
92 }