以下是一个整数栈类的定义:
const int SIZE=100;
class Stack
{
public:
Stack();
~Stack();
void Push(int n);
int Pop();
private:
int stack[SIZE];
int top;
};
编写一个栈的类模板(包括其成员函数定义),以便为任何类型的对象提供栈结构数据操作。并在主函数中测试创建整数栈、字符栈和浮点数栈,并提供一些数据展示入栈、出栈和打印操作。

c++栈的类模板,提供栈结构数据操作
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- _GX_ 2022-10-07 15:40关注
#include <iostream> #include <stdexcept> const int SIZE = 100; template <typename T> class Stack { public: Stack() : top(0) {} ~Stack() {} void Push(int n) { if (top == SIZE) throw std::runtime_error("stack is full"); stack[top++] = n; } int Pop() { if (top == 0) std::runtime_error("stack is empty"); return stack[--top]; } void Print() { for (int i = 0; i < top; i++) std::cout << stack[i] << " "; std::cout << '\n'; } private: T stack[SIZE]; int top; }; template <typename T> void test_stack() { std::cout << "test for " << typeid(T).name() << '\n'; Stack<T> si; for (int i = 'a'; i <= 'd'; i++) si.Push(i); si.Print(); si.Pop(); si.Print(); } int main() { try { test_stack<int>(); test_stack<char>(); test_stack<float>(); } catch (const std::exception &e) { std::cerr << e.what(); } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报