1、函数定义
#include <iostream> using namespace std; int add(int num1, int num2) { int sum = num1 + num2; return sum; } int main() { system("pause"); return 0; }
2、函数的调用
#include <iostream> using namespace std; int add(int num1, int num2) { int sum = num1 + num2; return sum; } int main() { int a = 10; int b = 20; int sum = add(a, b); cout << sum << endl; system("pause"); return 0; }
3、值传递
#include <iostream> using namespace std; void swap(int num1, int num2) { cout << "交换前" << endl; cout << "num1=" << num1 << endl; cout << "num2=" << num2 << endl; int temp = num1; num1 = num2; num2 = temp; cout << "交换后" << endl; cout << "num1=" << num1 << endl; cout << "num2=" << num2 << endl; } int main() { int a = 10; int b = 20; swap(a, b); cout << "a=" <<a<< endl; cout << "b=" << b << endl; system("pause"); return 0; }
4、函数的常见样式
#include <iostream> using namespace std; //1、无参无返 void test01() { cout << "this is test01" << endl; } //2、有参无返 void test02(int a) { cout << "this is test02 a = " << a << endl; } //3、无参有返 int test03() { cout << "this is test03" << endl; return 1000; } //4、有参有返 int test04(int a) { cout << "this is test04 a = " << a << endl; return a; } int main() { //无参无返的函数调用 test01(); //有参无返的函数调用 test02(100); //无参有返的函数调用 int num1=test03(); cout << "num1 = " << num1 << endl; //有参有返的函数调用 int num2=test04(10000); cout << "num2 = " << num2 << endl; system("pause"); return 0; }
5、函数声明
#include <iostream> using namespace std; int max(int a, int b); int main() { int a = 10; int b = 20; cout << max(a, b) << endl; system("pause"); return 0; } int max(int a, int b) { return a > b ? a : b; }
6、函数的分文件编写
函数分文件编写一般有4个步骤
1.创建后级名为.h的头文件
2.创建后缀名为.cpp的源文件
3.在头文件中写函数的声明
4.源文件中写函数的定义
swap.h
#include <iostream> using namespace std; void swap(int a, int b);
swap.cpp
#include "swap.h" void swap(int a, int b) { int temp = a; a = b; b = temp; cout << "a = " << a << endl; cout << "b = " << b << endl; }
main.cpp
#include <iostream> using namespace std; #include "swap.h" int main() { int a = 10; int b = 20; swap(a, b); system("pause"); return 0; }