C++分文件的编写函数
不分文件编写函数:
#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");
}
还没有评论,来说两句吧...