目录
1.定义语法
返回值类型 函数名 (参数列表)
{
函数主体
return表达式
}
函数定义中定义的参数为形参(形式参数),函数中,形参改变不会影响实参的值
2.常见样式
#include <iostream>
#include <string>
using namespace std;
//函数常见样式
//1.无参无返
void test01()
{
cout << "test01" << endl;
}
//2. 有参无返
void test02(int a)
{
cout << "a的值为" << a << endl;
}
//3. 无参有返
int test03()
{
cout << "test03" << endl;
return 100;
}
//有参有返
int test04(int num1, int num2)
{
num1 += num2;
cout << "num1=" << num1 << endl;
return num1;
}
int main()
{
test01();
test02(3);
int a = test03();
cout << a << endl;
a = test04(2, 5);
cout << a << endl;
system("pause");
return 0;
}
3.函数的分文件编写
步骤:
1.创建.h的头文件
2.在头文件声明函数
#include <iostream>
using namespace std;
//函数的声明
void test01();
void test02(int a);
int test03();
int test04(int num1, int num2);
3.创建在源文件定义函数
#include"hello.h"//关联头文件
//1.无参无返
void test01()
{
cout << "test01" << endl;
}
//2. 有参无返
void test02(int a)
{
cout << "a的值为" << a << endl;
}
//3. 无参有返
int test03()
{
cout << "test03" << endl;
return 100;
}
//有参有返
int test04(int num1, int num2)
{
num1 += num2;
cout << "num1=" << num1 << endl;
return num1;
}
4.在程序中引入定义的头文件
#include <iostream>
#include <string>
#include "hello.h"
using namespace std;
int main()
{
test01();
test02(3);
int a = test03();
cout << a << endl;
a = test04(2, 5);
cout << a << endl;
system("pause");
return 0;
}
4.VScode使用第三方库&自定义头文件
参考链接: