C++ Basics Chapter04 (written in separate files)

1. Writing in separate files
Function: Make the code structure clearer
Steps:
1) Create a header file with the suffix .h
2) Create a source file with the suffix .cpp
3) Write the function declaration in the header file
4) In the source Write the definition of the function in the file
Example:
1. Create a c++ file named Chapterer04.cpp

#include <iostream>
using namespace std;

#include "swap.h"

int main()
{
	int a = 10;
	int b = 20;
	
	swap(a, b);
}

2. Create a header file named swap.h

#include <iostream>
using namespace std;

//函数的声明
void swap(int a, int b);

3. Create a C++ file named 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;
}

Output result:

a=20
b=10

Guess you like

Origin blog.csdn.net/qq_43036676/article/details/100140226