CPP-模板范围错误

cpp - Template scope Error?

本文关键字:错误 范围 CPP-      更新时间:2023-10-16

我正在尝试使用模板在数组中实现基本堆栈。基于用户输入,形成了首选的堆栈类型。但是,在编译时,在检查IF条件下检查stack_type之后,它会出现"在此范围中声明s"的错误。如果评论条件检查,则不会显示任何错误。有人会介意解释为什么会遇到此错误吗?

#include<iostream>
using namespace std;
template < class Typ, int MaxStack >
class Stack {
        Typ items[MaxStack];
        int EmptyStack;
        int top;
        public:
                Stack();
                ~Stack();
                void push(Typ);
                Typ pop();
                int empty();
                int full();
};
template < class Typ, int MaxStack >
Stack< Typ, MaxStack >::Stack() {
        EmptyStack = -1;
        top = EmptyStack;
}
template < class Typ, int MaxStack >
Stack< Typ, MaxStack >::~Stack() {
         delete []items;
}
template < class Typ, int MaxStack >
void Stack< Typ, MaxStack >::push(Typ c) {
        items[ ++top ] = c;
}
template < class Typ, int MaxStack >
Typ Stack< Typ, MaxStack >::pop() {
        return items[ top-- ];
}
template< class Typ, int MaxStack >
int Stack< Typ, MaxStack >::full() {
        return top + 1 == MaxStack;
}
template< class Typ, int MaxStack >
int Stack< Typ, MaxStack >::empty() {
        return top == EmptyStack;
}
int main(void) {
        int stack_type;
        char ch;
        cout << "Enter stack type: nt1.tcharater stacknt2.tInteger stacknt3.tFloat stackn";
        cin >> stack_type;
        if(stack_type == 1)
                Stack<char, 10> s; // 10 chars
/*      if(stack_type == 2)
                Stack<int, 10> s; // 10 integers
        if(stack_type == 3)
                Stack<float, 10> s; // 10 double*/
        while ((ch = cin.get()) != 'n')
        if (!s.full())
                s.push(ch);
        while (!s.empty())
                cout << s.pop();
        cout << endl;
        return 0;
}
if(stack_type == 1)
   Stack<char, 10> s; // 10 chars

等效于:

if(stack_type == 1)
{
   Stack<char, 10> s; // 10 chars
}

s当然不是以下行中的范围。

我无法提出解决方案,因为您没有解释您希望在程序中完成的工作。