c++ - cpp - 模板范围错误?

标签 c++ templates scope stack

我正在尝试使用模板在数组中实现一个基本堆栈。根据用户输入,形成首选堆栈类型。但是在编译时,在 if 条件中检查 stack_type 后,它会给出错误“s was not declared in this scope”。如果注释了条件检查,则不会显示任何错误。有人介意解释为什么会出现此错误吗?

#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: \n\t1.\tcharater stack\n\t2.\tInteger stack\n\t3.\tFloat stack\n";
        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 当然不在下一行的范围内。

我无法提出修复建议,因为您尚未解释您希望在程序中完成的任务。

关于c++ - cpp - 模板范围错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42801546/

相关文章:

java - Guice 每个请求模块覆盖?

c++ - QWidget的内阴影效果

c++ - 对象的构造函数作为函数参数

c++ - 基于模式创建位掩码作为 constexpr

c++ - 模板模板参数的替换失败

c# - 内部方法和数据结构。

c++ - 选择了错误的功能

c++ - 根据参数在构造函数中设置成员数据类型

c++ - 如何根据 T::key_type 的定义专门化类模板?

javascript - 这个 add(x) 函数如何工作?