我只是想对我的Stack的C++实现提供一些反馈。我知道这有点凌乱,但我正在尝试改进我使用类的方式。我很确定我没有正确使用模板。希望对堆栈实现有一些反馈C++
欢迎任何建议!
#include <iostream>
#include </root/Dev/Stack.h>
#include<string>
using namespace std;
template<class T>
Stack<T>::Stack(T &size)
{
capacity = size;
if(size==0)
{
cout<<"Capacity can't be zero!"<<endl;
stack = 0;
}
else
{
stack = new T[capacity];
}
count = -1;
}
template<class T>
void Stack<T>::Insert(T &data)
{
if (count == (capacity-1))
{
cout<<"Stack is full";
return;
}
else
{
count++;
stack[count] = data;
}
}
template<class T>
void Stack<T>::Display()
{
cout << "Printing out values:" << endl;
for (int i=0; i<count; i++)
cout << stack[i] << endl;
}
int main()
{
Stack<int> S1(5);
S1.Insert(10);
S1.Insert(22);
S1.Insert(5522);
S1.Display();
Stack<string> S2(6);
S2.Insert("hi");
S2.Insert("Savvy");
S2.Insert("How are you?");
S2.Display();
return 0;
}
头文件:
#include<iostream>
using namespace std;
template<class T>
class Stack {
public:
int capacity;
int count;
T *stack;
void Insert(T &num);
void Display();
Stack(T &value);
};
@CaptainObvlious请投票结束为“太宽泛”。投票结束,因为问题属于另一个网站并不是一个有效的密切原因。 –
@EthanBierlein这肯定是一个有效的原因。这里只是关注主题,但在其他主题上。 –
@KubaOber不,它*不是一个有效的密切原因。*如果有一个比它更好的并且已经内置的紧密原因,那么它应该被使用。 –