C++ 实现模板类Stack1
下面的链接是一张显示类骨架的图片 这就是我目前所知道的我想知道的是我所做的是否在正确的方向上。 我首先创建了一个名为ItemType的模板,然后创建了一个名为Stack1的类。 在Stack1中,我有两个私有类成员,一个是ItemType指针(info)和一个整数(top),然后我创建了一个默认构造函数,并为我的类成员和一个复制构造函数赋值,该构造函数接受类对象的引用C++ 实现模板类Stack1,c++,C++,下面的链接是一张显示类骨架的图片 这就是我目前所知道的我想知道的是我所做的是否在正确的方向上。 我首先创建了一个名为ItemType的模板,然后创建了一个名为Stack1的类。 在Stack1中,我有两个私有类成员,一个是ItemType指针(info)和一个整数(top),然后我创建了一个默认构造函数,并为我的类成员和一个复制构造函数赋值,该构造函数接受类对象的引用 #include "pch.h" #include <iostream> using namespace st
#include "pch.h"
#include <iostream>
using namespace std;
template<class ItemType>
class Stack1
{
private:
ItemType* info;
int top;
public:
Stack1()
{
int MAXITEM = 5;
top = -1;
info = new int[MAXITEM];
}
Stack1(const Stack1<ItemType> &x)
{
int* copy;
copy = new int[x.MAXITEM];
for (int i = 0; i < 5; i++)
{
copy[i] = x.info[i];
}
}
void push(ItemType x)
{
top++;
info[top] = x;
}
void print()
{
for (int i = 0; i < 5; i++)
{
cout << info[i] << " " << endl;
}
}
void MakeEmpty()
{
for (int i = 0; i < 5; i++)
{
info[top] = NULL;
top--;
}
}
};
int main()
{
Stack1 <int> X;
X.push(2);
X.push(5);
X.push(8);
X.push(7);
X.push(10);
X.print();w
Stack1 <int> X2;
X2 = X;
X2.print();
X.MakeEmpty();
X.print();
}
#包括“pch.h”
#包括
使用名称空间std;
模板
第1类
{
私人:
项目类型*信息;
int top;
公众:
Stack1()
{
int MAXITEM=5;
top=-1;
信息=新的整数[MAXITEM];
}
Stack1(常数Stack1和x)
{
int*副本;
复制=新整数[x.MAXITEM];
对于(int i=0;i<5;i++)
{
复制[i]=x.info[i];
}
}
无效推送(项目类型x)
{
top++;
info[top]=x;
}
作废打印()
{
对于(int i=0;i<5;i++)
{
你为什么要假设ItemType
和int
总是同义的呢?这样做会破坏模板的作用,不是吗?info=new int[MAXITEM];
例如,这应该是info=new ItemType[MAXITEM];
。此外,没有MAXITEM
成员变量(静态或其他),因此不知道您希望使用copy=new int[x.MAXITEM];
。无论如何,您似乎忘记了在您的帖子中提问。info[top]=NULL;
不是清空数组的方法。ItemType
可能不喜欢使用NULL
(或首选的nullptr
)分配给它。现在,只需在MakeEmpty
中重置top
。