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;
}
相关推荐
阿沁QWQ9 分钟前
单例模式的两种设计
开发语言·c++·单例模式
六bring个六16 分钟前
qtcreater配置opencv
c++·qt·opencv·计算机视觉·图形渲染·opengl
qwertyuiop_i21 分钟前
pe文件二进制解析(用c/c++解析一个二进制pe文件)
c语言·c++·pe文件
yxc_inspire1 小时前
基于Qt的app开发第八天
开发语言·c++·qt
June`2 小时前
专题三:穷举vs暴搜vs深搜vs回溯vs剪枝(全排列)决策树与递归实现详解
c++·算法·深度优先·剪枝
我叫珂蛋儿吖2 小时前
[redis进阶六]详解redis作为缓存&&分布式锁
运维·c语言·数据库·c++·redis·分布式·缓存
yxc_inspire3 小时前
基于Qt的app开发第七天
开发语言·c++·qt·app
周Echo周3 小时前
20、map和set、unordered_map、un_ordered_set的复现
c语言·开发语言·数据结构·c++·算法·leetcode·list
☆平常心☆4 小时前
UE5通过C++实现TcpSocket连接
c++·ue5
dot to one5 小时前
Qt 中 QWidget涉及的常用核心属性介绍
开发语言·c++·qt