1.加法函数的实现
#include <iostream>
using namespace std;
int add(int a, int b)
{
int sum = a + b;
return sum;
}
int main()
{
int c = add(123,432);
cout << c << endl;
system("pause");
return 0;
}
2.值传递
#include <iostream>
using namespace std;
//定义函数,实现两数字交换
void swap(int num1,int num2)
{
int temp;
cout << "交换前: " << endl;
cout << "num1 = " << num1 << endl; //num1 =10
cout << "num2 = " << num2 << endl; //num2 = 20
temp = num1;
num1 = num2;
num2 = temp;
cout << "交换后: " << endl;
cout << "num1 = " << num1 << endl; //num1 = 20
cout << "num2 = " << num2 << endl; //num2 = 10
return;//可以不写
}
int main()
{
int a = 10;
int b = 20;
cout << "调用函数前" << endl;
cout << "a = " << a << endl; //a = 10
cout << "b = " << b << endl; //b = 20
//当函数作值传递时,函数的形参发生改变,并不会影响实参
swap(a, b);
cout << "调用函数后" << endl;
cout << "a = " << a << endl; //a = 10
cout << "b = " << b << endl; //b = 20
system("pause");
return 0;
}
3.函数的声明
#include <iostream>
using namespace std;
//声明可以有多次,定义只能一次
int max(int a, int b);
int main()
{
int maxnum = max(10, 20);
cout << maxnum << endl;
system("pause");
return 0;
}
int max(int a, int b)
{
return a > b ? a : b;
}
4.函数的分文件编写 (1)创建后缀名为.h的文件 (2)创建后缀名为.cpp的文件 (3)在头文件中写函数的声明 (4)在源文件中写函数的定义
|