多文件
-
一个源程序可以划分为多个源文件
-
类声明文件(.h文件)
-
类实现文件(.cpp文件)
-
类的使用文件(main()所在的.cpp文件)
-
-
利用工程来组合各个文件
ATTENTION
vscode中多文件编译运行
![]()
![]()
vscode的c++配置及多文件项目编译(主要是后者) - 知乎 (zhihu.com)
Example 1. 多文件,利用类表示栈
![image-20211119183345700](comb.assets/image-20211119183345700.png)
“stack.h”
#include <iostream>
#include <iomanip>
#include <ctype.h>
const int SIZE = 10;
class stack
{
int stck[SIZE]; //数组,用于存放栈中数据
int tos; //栈顶位置(数组下标)
public:
stack();
void push(int ch); //将数据ch压入栈
int pop(); //将栈顶数据弹出栈
void ShowStack();
};
“stack.cpp”
//#include <iostream>
#include "stack.h"
using namespace std;
stack::stack() { tos = 0; }
void stack::push(int ch)
{
if (tos == SIZE)
{
cout << "Stack is full" << endl;
return;
}
stck[tos] = ch;
tos++;
cout << "You have pushed a data into the stack!" << endl;
}
int stack::pop()
{
if (tos == 0)
{
cout << "Stack is empty" << endl;
return 0;
}
tos--;
return stck[tos];
}
void stack::ShowStack()
{
cout << "The content of stack: " << endl;
if (tos == 0)
{
cout << "The stack has no data!" << endl;
return;
}
for (int i = tos - 1; i >= 0; i--)
{
cout << stck[i] << " ";
}
cout << endl
<< endl;
}
“stackmain.cpp”
#include <iostream>
using namespace std;
#include "stack.h"
int main()
{
cout << endl;
stack ss;
int x;
char ch;
cout << "<I>------Push data to stack" << endl;
cout << "<O>------Pop data from stack" << endl;
cout << "<S>------Show the content of stack" << endl;
cout << "<Q>------Quit..." << endl;
while (1)
{
cout << "Please select an item: ";
cin >> ch;
ch = toupper(ch);
switch (ch)
{
case 'I':
cout << "Enter the value that you want to push: ";
cin >> x;
ss.push(x);
break;
case 'O':
x = ss.pop();
cout << "Pop " << x << " from stack" << endl;
break;
case 'S':
ss.ShowStack();
break;
case 'Q':
return 0;
default:
cout << "You have inputted a wrong item! Please try again!" << endl;
break;
}
}
return 0;
}
测试结果
<I>------Push data to stack
<O>------Pop data from stack
<S>------Show the content of stack
<Q>------Quit...
Please select an item: I
Enter the value that you want to push: 1
You have pushed a data into the stack!
Please select an item: I
Enter the value that you want to push: 2
You have pushed a data into the stack!
Please select an item: I
Enter the value that you want to push: 6
You have pushed a data into the stack!
Please select an item: S
The content of stack:
6 2 1
Please select an item: O
Pop 6 from stack
Please select an item: S
The content of stack:
2 1
Please select an item: O
Pop 2 from stack
Please select an item: S
The content of stack:
1
Please select an item: Q