c++day6

尝试使用模板类,实现顺序栈。

cpp 复制代码
#include <iostream>
#define MAX 8
using namespace std;
typedef struct{
    int a;
    int b;
}test_t;

template <typename T>
class Stack
{
private:
    T *data;
    int top;
public:
    Stack() :data(nullptr),top(-1){}
    //创建顺序栈
    int create_stack();
    //出栈
    int pop_stack();
    //入栈
    int push_stack(T data);
    //遍历
    int show_stack();
    //释放顺序表
    int free_stack();
};
template <typename T>
int Stack<T>::create_stack(){
    this->data=new T[MAX];
    this->top=-1;
    return 0;
}
template <typename T>
int Stack<T>::pop_stack(){
    if(this->data==nullptr||this->top==-1){
        cout<<"入参错误"<<endl;
        return -1;
    }
    cout<<this->data[this->top]<<endl;
    this->top--;
    return 0;
}
template <typename T>
int Stack<T>::push_stack(T data){
    if(this->data==nullptr){
        cout<<"入参错误"<<endl;
        return -1;
    }
    top++;
    this->data[this->top]=data;
    return 0;
}
void show(test_t data){
    cout<<"a="<<data.a<<" "<<"b="<<data.b<<endl;
}
template <typename T>
int Stack<T>::show_stack(){
    if(this->data==nullptr){
        cout<<"入参错误"<<endl;
        return -1;
    }
    for(int i=this->top;i>=0;i--){
        show(*(data+i));
    }
    return 0;
}
template <typename T>
int Stack<T>::free_stack(){
    if(this->data==nullptr){
        cout<<"入参错误"<<endl;
        return -1;
    }
    delete []this->data;
    return 0;
}
int main()
{

    Stack<test_t> s;
    test_t t1={10,20};
    test_t t2={30,40};
    test_t t3={50,60};
    s.create_stack();
    s.push_stack(t1);
    s.push_stack(t2);
    s.push_stack(t3);
    s.show_stack();
//    s.pop_stack();
    s.free_stack();
    return 0;
}

异常处理

cpp 复制代码
#include <iostream>

using namespace std;
int fun(int a,int b){
    if(0==b){
        throw int(1);
    }
    return a/b;
}

int main()
{
    try {
        fun(2,0);
    } catch (int a) {
        if(a==1){
            cout<<"除数为0"<<endl;
        }
    }
    cout<<"hello"<<endl;
    return 0;
}
相关推荐
Lumbrologist7 小时前
【C++】零基础入门 · 第 1 节:第一个程序 Hello World 与编译运行
开发语言·c++
_李小白8 小时前
【C++学习笔记】新特性之inline变量
c++·笔记·学习
桀人8 小时前
C++——模板初阶(收录在专栏C++入门到精通)
开发语言·c++
Lumbrologist9 小时前
【C++】零基础入门 · 第 2 节:变量、基本数据类型与输入输出
java·开发语言·c++
XX風9 小时前
CMake / Make / Ninja / MSVC / GCC / Clang / MSBuild —— 完整体系化理解
c++
Peter·Pan爱编程9 小时前
10. new_delete 不是 malloc_free 的包装
c++·人工智能·算法
故事和你9111 小时前
洛谷-【动态规划1】动态规划的引入2
开发语言·数据结构·c++·算法·动态规划·图论
fpcc11 小时前
c++编程实践——历史记录的管理
c++
玖笙&12 小时前
✨WPF编程基础【3.3】:容器控件(附源码)
c++·wpf·visual studio
汉克老师13 小时前
GESP5级C++考试语法知识(十七、二分算法提高篇(二))
c++·算法·二分算法·gesp5级·gesp五级·二分算法易错点