DAY3,C++(结构体,类,this指针,类中特殊的成员函数)

该文描述了一个手动封装的顺序栈类,数据元素为整型。栈类包含私有成员属性,如指向堆区存储数据的指针和栈顶元素的变量。文章展示了如何使用这个栈类进行入栈、出栈、判断栈空栈满、遍历栈以及获取栈顶元素等操作。
摘要由CSDN通过智能技术生成

1.手动封装一个顺序栈类(数据元素为整形),要求私有成员属性:堆区空间的指针,用于存放数据,和一个指向栈顶元素的变量;

 ---main.cpp---主函数
#include "stack.h"

int main()
{
    int size;
    cout<<"输入栈大小>>> ";
    cin>>size;

    My_stack sta(size);  //调用有参构造

    char ch;
    int elem;
    do         //入栈
    {
        cout<<"输入入栈元素>>> ";
        cin>>elem;
        sta.my_push(size,elem);

        if(sta.my_full(size) == true)
            break;

        cout<<"继续入栈? y/Y ";
        cin>>ch;
    }while(ch == 'y' || ch =='Y');

    sta.my_loop();  //遍历栈
    cout<<"栈顶元素>>> "<<sta.get_top()<<endl;;  //获取栈顶元素

    cout<<"删除两个元素后---"<<endl;
    sta.my_pop();  //出栈
    sta.my_pop();

    sta.my_loop();  //遍历栈

    cout<<"栈顶元素>>> "<<sta.get_top()<<endl;  //获取栈顶元素

    return 0;
}
---stack.h---头文件
#ifndef STACK_H
#define STACK_H

#include <iostream>

using namespace std;

class My_stack
{
private:
    int *ptr;  //指向堆区空间
    int top;  //记录栈顶元素

public:
    My_stack():ptr(new int[10]),top(-1){}  //无参构造
    My_stack(int size):ptr(new int[size]),top(-1){}  //有参构造
    ~My_stack(){delete [] ptr;}

    bool my_empty();    //判空函数
    bool my_full(int size);  //判满函数;
    void my_push(int size,int elem);    //入栈函数
    void my_pop();  //出栈//出栈函数
    void my_loop();  //遍历栈
    int get_top();  //获取栈顶元素
};

#endif // STACK_H
---stack.cpp---实现函数
#include "stack.h"

bool My_stack::my_empty()  //判空
{
    return top == -1;
}

bool My_stack::my_full(int size)  //栈满
{
    return top == (size-1);
}

void My_stack::my_push(int size,int elem)  //入栈
{
    if(!my_full(size))
        ptr[++top] = elem;
    else
    {
        cout<<"栈满"<<endl;
        return;
    }
}

void My_stack::my_pop()  //出栈
{
    if(!my_empty())
        top--;
    else
    {
        cout<<"栈空"<<endl;
        return;
    }
}

void My_stack::my_loop()  //遍历
{
    if(!my_empty())
    {
        for(int i=top; i>=0; i--)
        {
            cout<<ptr[i]<<" ";
        }
        cout<<endl;
    }
}

int My_stack::get_top() //获取栈顶元素
{
    if(!my_empty())
        return ptr[top];
}

 

2.今日脑图 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值