Итак, я понимаю, что есть множество других вопросов, подобных этому, но я искал около 2 часов и еще не нашел того, который работал бы для меня. В этом коде я пытаюсь создать простой стек, используя шаблон класса; Тем не менее, я получаю сообщение об ошибке: Неправильное использование элементов данных c, не относящихся к состоянию при попытке объявить указатель на мой массив (T * Arr). Я получаю ту же ошибку при инициализации моего int ArrTop, но не мой int ArrSize? Наконец, я также получаю, что ошибки не могут вызвать функцию-член без объекта, когда я пытаюсь вызвать Top () и Empty () из файла. cpp. Любая помощь будет принята с благодарностью!
Вот код:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
const int DEFAULTSIZE=100;
template <class T>
class Stack {
public:
Stack(); // Default Constructor, stack is size 100.
Stack(const int size); // Constructor, creates stack of size "size"
Stack(const Stack<T> & item);// Copy constructor
bool Full(); // Return true if the stack is full
bool Empty(); // Return true if the stack is empty
int Size(); // Return the size of the stack
T Top(); // Returns the top element, does not pop it.
bool Push (const T item); // Put an item on the stack.
bool Pop(); // Pop an item off and display to std out
friend ostream &operator <<(ostream & os, Stack<T> &s)
{
if(Empty())
{
cout<<"Stack underflow!";
}
else
{
cout<<"Element: "<<Top()<<"has been removed"<<endl;
Arr[ArrTop--];
}
}
private:
T *Arr; // The "stack"
int ArrSize; // The number of elements the stack can hold
int ArrTop; // Points to the first empty node
};
template <class T>
Stack<T>::Stack()
{
Arr = new T[DEFAULTSIZE];
ArrSize = DEFAULTSIZE;
ArrTop = -1;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
template <class T>
Stack<T>::Stack(const int size)
{
Arr = new T[size];
ArrSize=size;
ArrTop = -1;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
template <class T>
bool Stack<T>::Empty()
{
if(ArrTop==-1)
return true;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
template <class T>
int Stack<T>::Size()
{
return ArrTop+1;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
template <class T>
bool Stack<T>::Full()
{
if(Size()==ArrSize)
return true;
}
template <class T>
bool Stack<T>::Pop()
{
if(Empty())
{
cout<<"Stack underflow!";
return false;
}
cout<<"Element: "<<Top()<<"has been removed"<<endl;
Arr[ArrTop--];
return true;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
template <class T>
T Stack<T>::Top()
{
if(!Empty())
{
return Arr[ArrTop];
}
else
{
exit(EXIT_FAILURE);
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
template <class T>
bool Stack<T>::Push(const T item)
{
if(Full())
{
cout<<"Stack overflow!";
return false;
}
else
{
cout<<"Element: "<<item<<"has been inserted!"<<endl;
Arr[ArrTop++]=item;
}
}
Тогда появляются ошибки, которые я получаю:
In file included from main.cpp:2:0:
stack.cpp: In function ‘std::ostream& operator<<(std::ostream&, Stack<T>&)’:
stack.cpp:45:9: error: invalid use of non-static data member ‘Stack<T>::Arr’
T *Arr; // The "stack"
^
stack.cpp:40:3: error: from this location
Arr[ArrTop--];
^
stack.cpp:47:10: error: invalid use of non-static data member ‘Stack<T>::ArrTop’
int ArrTop; // Points to the first empty node
^
stack.cpp:40:7: error: from this location
Arr[ArrTop--];
^
stack.cpp: In instantiation of ‘std::ostream& operator<<(std::ostream&, Stack<char>&)’:
main.cpp:29:16: required from here
stack.cpp:33:11: error: cannot call member function ‘bool Stack<T>::Empty() [with T = char]’ without object
if(Empty())
^
stack.cpp:39:26: error: cannot call member function ‘T Stack<T>::Top() [with T = char]’ without object
cout<<"Element: "<<Top()<<"has been removed"<<endl;
^
make: *** [main.o] Error 1
Еще раз спасибо, ребята так много, ты лучший!