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;
}
相关推荐
努力实干8 小时前
面向对象设计原则——C++
开发语言·c++·数码相机
syagain_zsx11 小时前
jsoncpp 使用指南:编译链接、Json::Value 取值与高频坑
c++·json·库·http格式
布莱克60512 小时前
理解 = delete 与 = default:两种赋值语义的差异
c++
小小、码农13 小时前
[特殊字符]【C++11】类的新功能全面解析:移动构造、移动赋值、default、delete、final 与 override
linux·开发语言·网络·c++
库玛西13 小时前
外部排序全解析:败者树、置换-选择排序与最佳归并树
c语言·数据结构·c++·笔记·考研·算法
General_G15 小时前
创建型模式—原型(Prototype)模式
c++·设计模式·原型模式
syagain_zsx15 小时前
protobuf 实战:从 .proto 到 C++ 序列化的完整链路
c++·学习·程序人生·谷歌·protobuf
welfare96215 小时前
新号别搞:C++_list
开发语言·c++
xiaoye-duck16 小时前
《C++ 项目:手写大模型接入 SDK》云端 API 调用基础与 Apifox 调试实战
网络·c++·语言模型
坤坤子吖16 小时前
Linux 线程同步与互斥——条件变量与线程同步
linux·开发语言·c++·笔记·学习