C++怎么类外定义模板类的成员函数? 模板参数怎么调用?

2025-04-02 03:13:12
推荐回答(3个)
回答(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

调用的方法,如下:

#include

#include"stack.h"

int main()
{
 Stack charStack;
 charStack.push('h');
 charStack.peek();
 charStack.pop();
 charStack.clearStack();

 return EXIT_SUCCESS;
}

回答(2):

包含模板的声明

回答(3):

找哟个有钱的干爹