C++一个类模板的成员函数调用另一个类的模板成员函数

2025-03-13 00:47:45
推荐回答(1个)
回答1:

#ifndef STACK_H
#define STACK_H

#include
#include

/**
* 栈
*/
template
class Stack
{
public:
Stack();

public:
/**
* 元素入栈
* @param item 需要入栈的元素
*/
void push(const ItemType& item);

/**
* 栈顶元素出栈
* @return 栈顶的元素
*/
ItemType pop();

/**
* 获取栈顶元素
* 栈顶元素
*/
ItemType peek() const;

/**
* 清空栈
*/
void clearStack();

private:
/**
* 栈是否为空
* @return true 栈为空;false 栈不为空
*/
bool isEmpty() const;

/**
* 栈是否为满
* @return true 栈为满;false 栈不为满
*/
bool isFull() const;

private:
/**
* 栈的大小
*/
static const int maxStackSize = 50;

private:
/**
* 栈
*/
ItemType array[maxStackSize];

/**
* 栈顶标识
*/
int top;
};

template
Stack::Stack() : top(-1)
{}

template
void Stack::push(const ItemType& item)
{
if (isFull())
{
std::cerr << "Stack overflow!" << std::endl;
exit(EXIT_FAILURE);
}
top++;
array[top] = item;
}

template
ItemType Stack::pop()
{
if (isEmpty())
{
std::cerr << "Attempt to pop an empty stack!" << std::endl;
exit(EXIT_FAILURE);
}
ItemType temp = array[top];
top--;

return temp;
}

template
ItemType Stack::peek() const
{
if (isEmpty())
{
std::cerr << "Attempt to peek an empty stack!" << std::endl;
exit(EXIT_FAILURE);
}
return array[top];
}

template
bool Stack::isEmpty() const
{
return (top == -1 ? true : false);
}

template
bool Stack::isFull() const
{
return (top == (maxStackSize - 1) ? true : false);
}

template
void Stack::clearStack()
{
//将所有元素弹出栈
while (!isEmpty())
{
pop();
}
}

#endif //STACK_H