C++怎么类外定义模板类的成员函数? 模板参数怎么调用?
答案:3 悬赏:80 手机版
解决时间 2021-04-05 13:20
- 提问者网友:孤山下
- 2021-04-04 21:46
C++怎么类外定义模板类的成员函数? 模板参数怎么调用?
最佳答案
- 五星知识达人网友:一叶十三刺
- 2021-04-04 22:45
#ifndef STACK_H
#define STACK_H
#include
#include
template
class Stack
{
public:
Stack();
public:
void push(const ItemType& item);
ItemType pop();
ItemType peek() const;
void clearStack();
private:
bool isEmpty() const;
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;
}
#define STACK_H
#include
#include
template
class Stack
{
public:
Stack();
public:
void push(const ItemType& item);
ItemType pop();
ItemType peek() const;
void clearStack();
private:
bool isEmpty() const;
bool isFull() const;
private:
static const int maxStackSize = 50;
private:
ItemType array[maxStackSize];
int top;
};
template
Stack
{}
template
void Stack
{
if (isFull())
{
std::cerr << "Stack overflow!" << std::endl;
exit(EXIT_FAILURE);
}
top++;
array[top] = item;
}
template
ItemType Stack
{
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
{
if (isEmpty())
{
std::cerr << "Attempt to peek an empty stack!" << std::endl;
exit(EXIT_FAILURE);
}
return array[top];
}
template
bool Stack
{
return (top == -1 ? true : false);
}
template
bool Stack
{
return (top == (maxStackSize - 1) ? true : false);
}
template
void Stack
{
//将所有元素弹出栈
while (!isEmpty())
{
pop();
}
}
#endif //STACK_H调用的方法,如下:
#include
#include"stack.h"
int main()
{
Stack
charStack.push('h');
charStack.peek();
charStack.pop();
charStack.clearStack();
return EXIT_SUCCESS;
}
全部回答
- 1楼网友:山有枢
- 2021-04-05 00:37
包含模板的声明
- 2楼网友:西岸风
- 2021-04-05 00:08
找哟个有钱的干爹
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯