给定这个示例类模板:
template<typename T>
class Stack {
T * data;
int size;
int nextIndex;
public:
Stack(int size = 100);
Stack(const Stack& stack);
~Stack();
Stack& operator=(const Stack& s);
void push(const T& t);
void pop();
T& top();
const T& top() const;
int getSize() const;
class Full {
};
class Empty {
};
};
template<typename T>
void Stack::push(const T& t) {
if (nextIndex >= size) {
throw Full();
}
data[nextIndex++] = t;
}
template<typename T>
void Stack::pop() {
if (nextIndex <= 0) {
throw Empty();
}
nextIndex--;
}
push
的实现部分可以吗?和 pop
方法?
不明白要不要写void Stack<T>::push(const T& t)
而不是 void Stack::push(const T& t)
(对于 pop
方法也是如此)。
注意:Eclipse(根据 C++11)给我下一个错误:
Member declaration not found
因为这些行:
void Stack::push(const T& t) {
void Stack::pop() {
最佳答案
The part of the implementaion of push method and pop method it's ok? I don't understand if I need to write void Stack::push(const T& t) instead void Stack::push(const T& t) (and the same for pop method).
你需要使用
template <typename T>
void Stack<T>::push(const T& t) { ... }
template <typename T>
void Stack<T>::pop() { ... }
名字Stack
与Stack<T>
相同当它用作类型名时,在类模板定义中。在类模板定义之外,您必须显式提供模板参数。
关于c++ - 什么时候写模板尖括号(<...>)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49285264/