不分文件編寫函數:
#include<iostream>
using namespace std;
//函數的聲明
void swap(int a, int b);
//函數的定義
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
cout << "a的值" << a << endl;
cout << "b的值" << b << endl;
}
int main() {
int a = 10;
int b = 20;
swap(a, b);
system("pause");
}
分文件編寫函數:
1、創建.h後綴名的頭文件
2、 創建. cpp後綴名的源文件
3、 在頭文件中寫函數的聲明
//函數的聲明
void swap(int a, int b);
4、在源文件中寫函數的定義
#include<iostream>
#include "swap.h"
using namespace std;
//函數的定義
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
cout << "a的值" << a << endl;
cout << "b的值" << b << endl;
}
5,在main函數中引入自定義函數的頭文件
#include<iostream>
#include"swap.h"
using namespace std;
int main() {
int a = 10;
int b = 20;
swap(a, b);
system("pause");
}