1样例
创建一个栈类,用来保存数据和删除


CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(Stack_Test)
#1手动设置指定文件
#set(Current_LIST main.cpp)
#2自动搜所文件目录
aux_source_directory(. Current_LIST) # 搜索当前.目录下的所有.cpp文件
aux_source_directory(./src SRC_LIST) # 搜索当前.目录下的所有.cpp文件
include_directories(src)#关键 不是相对引用 需要单独制定包含
# 4指定生成目标
add_executable(Stack_demo ${Current_LIST} ${SRC_LIST})
main.cpp
#ifndef MAIN_CPP
#define MAIN_CPP
//#include "API_stack.h" //关键地方 不是相对引用 src/API_Cout.h cmakelist.txt需要加包含文件include_directories
#include "src/API_stack.h" //关键地方 相对引用 src/API_Cout.h cmakelist.txt不需要加包含文件include_directories
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
Stack st;
char ch;
unsigned long po;
cout<<"paleas enter A to add a data \n"
<<"P to pop a data \n"
<<"Q to quit"<<endl;
while(cin >> ch && toupper(ch) != 'Q') //等待输入 且不为Q 退出
{
while(cin.get() != '\n')//等待回车确认 换行符号
continue;
if(!isalpha(ch))//检查c是否为字母。
{
cout<< '\a'<<"input is not char "<<endl; //凤鸣报警
continue;
}
switch(ch)
{
case 'A':
cout<< "enter a number to add";
cin>> po;
if(st.isfull())
cout<< "stack already full\n"<<endl;
else
{
st.push(po);
}
break;
case 'P':
if(st.isempty())
cout<<"stack alread empty"<<endl;
else
{
st.pop(po);
cout<<"Po "<< po<<"popped\n";
}
break;
}
cout<<"paleas enter A to add a data \n"
<<"P to pop a data \n"
<<"Q to quit"<<endl;
}
cout<<"Bye" <<endl;
return 0;
}
#endif

API_stack.h
#ifndef STACK_H
#define STACK_H
#include <string>
#include <iostream>
typedef unsigned long Item;
class Stack
{
private:
enum{MAX=10};
Item items[MAX];
int top;
public:
Stack();
~Stack();
bool isempty() const;
bool isfull() const;
bool push(const Item &item);
bool pop(Item &item);
};
#endif
API_stack.cpp
#ifndef STACK_CPP
#define STACK_CPP
#include "API_stack.h"
Stack::Stack()
{
top=0;
}
Stack::~Stack()
{
using namespace std;
cout<<"class is over"<<endl;
}
bool Stack::isempty() const
{
return top==0;
}
bool Stack::isfull() const
{
return top==MAX;
}
bool Stack::push(const Item &item)
{
if(top<MAX)
{
items[top++]=item;
return true;
}
else
{
return false;
}
}
bool Stack::pop(Item &item)
{
if(top >0)
{
item=items[--top];
return true;
}
else
return false;
}
#endif
编译
cd build cmake .. make ./Stack_demo

浙公网安备 33010602011771号