基于std::vector私有继承的Stack类C++实现疑问
基于私有继承std::vector的Stack类实现
因为是私有继承std::vector<T>,所以在类的成员函数中可以直接调用基类的成员,但需要显式指明(或通过this->访问)。以下是头文件对应的.cpp实现:
#include "Stack.h" template <typename T> Stack<T>::Stack() : std::vector<T>() {} // 显式调用基类构造函数,也可空实现(编译器自动生成默认构造) template <typename T> Stack<T>::~Stack() {} // 基类析构函数会自动被调用,无需额外操作 template <typename T> bool Stack<T>::empty() const { return std::vector<T>::empty(); // 等价于 return this->empty(); } template <typename T> size_t Stack<T>::size() const { return std::vector<T>::size(); // 等价于 return this->size(); } template <typename T> void Stack<T>::push(const T& item) { std::vector<T>::push_back(item); } template <typename T> void Stack<T>::pop() { if (empty()) { throw std::underflow_error("Stack underflow: cannot pop from empty stack"); } std::vector<T>::pop_back(); } template <typename T> const T& Stack<T>::top() const { if (empty()) { throw std::underflow_error("Stack underflow: cannot access top of empty stack"); } return std::vector<T>::back(); } // 注意:模板类的实现通常需放在头文件中,若必须分开编译,需添加显式实例化代码,例如: // template class Stack<int>; // template class Stack<std::string>;
关键说明:
- 私有继承下,基类的所有成员在派生类中均为私有访问权限,仅能在
Stack类的成员函数内部调用std::vector的方法。 pop和top函数必须先判断栈是否为空,按要求抛出std::underflow_error异常。- 模板类若单独放在cpp文件编译,必须显式实例化需要用到的类型,否则会出现链接错误。
内容的提问来源于stack exchange,提问作者Lucia
相关产品推荐
相关产品推荐

