【发布时间】:2017-11-21 12:39:40
【问题描述】:
我知道在代码中查找错误不是在 StackOverflow 中完成的,但我在这里发帖是因为我真的很绝望,因为我一直在寻找解决方案现在完全没有结果。
我的任务是实现我自己的 Stack 类(作为链表)。那部分没问题。这是我的代码
template<typename T>
struct node {
T inf;
node* link;
};
template <typename T>
class myStack {
private:
node<T> *start; //Decalration of class myStack. I've left only the default constructor.
public:
myStack();
}
template<typename T>
myStack<T>::myStack() {
start = NULL;
}
一切都按预期进行。任务的下一部分是使用两个堆栈实现一个队列。基本上,入队意味着将一个元素推入第一个堆栈,然后将所有元素从第一个堆栈转移到第二个堆栈,然后弹出顶部一个。
队列的实现:
template<class T>
class QueueStacks {
myStack<T> stack1;
myStack<T> stack2;
public:
QueueStacks();
void enqueue(T&);
T& dequeue();
void print();
};
template<typename T>
QueueStacks<T>::QueueStacks() { //No need I believe, for default constructor, but I left it for clarity purposes
}
template<typename T>
void QueueStacks<T>::enqueue(T& obj) {
if (stack1.empty()) {
transferTwoToOne(); //Function transferTwoToOne works as intended, so I didn't deem it necessary to include include its implementation
}
else {
stack1.push(); //void myStack::push() works as intended, so I deliberately left out its implmentation
}
}
template<typename T>
T& QueueStacks<T>::dequeue() {
T x;
if (stack1.empty() && stack2.empty()) {
cout << "Attempt to pop from an empty stack";
}
else {
if (stack2.empty()) {
transferOneToTwo(); //Same for function transferOneToTwo
stack2.pop(x);
}
else
stack2.pop(x); //same for pop
return x;
}
}
template<typename T>
void QueueStacks<T>::print() {
T x;
if (stack2.empty()) {
transferOneToTwo();
}
while (!stack2.empty()) {
stack2.pop(x);
cout << x << " ";
}
}
当我尝试从类队列初始化对象时出现错误。例如
int main()
{
QueueStacks<int> obj1;
for (int i = 0; i < 5; i++){
obj1.push(i);
}
obj1.print();
return 0;
}
编译器显示如下:注意:请参阅对正在编译的类模板实例化“QueueStacks”的引用。我有 3 个错误:
尝试初始化 obj1 时我做错了什么?
【问题讨论】:
-
创建一个minimal reproducible example 并逐字粘贴整个错误