c++ - 无法从类内的其他函数访问同一类的变量

标签 c++ class dynamic-memory-allocation

我无法从类中的其他推送和弹出函数访问我的“arr”变量。收到错误“'arr'未在此范围内声明”。 它应该可以在类里面访问。我可以静态分配内存作为解决方案,但我想试试这个。

该程序给出了反向波兰符号。
输入
1
(a+b)
啊/啊
ab+

#include <iostream>
#include <string>
using namespace std;


class stackOperations{
  private:
    int top = -1 ;
  public:
  void allocate(int len){
    char *arr = new char[len] ;
  }
  void deallocate(){
    delete []arr ;
  }
  void push(char x){
      top++;
      arr[top] = x ;
  }
  char pop()
  {
      char temp;
      temp = arr[top];
      top--;
      return temp;
  }
};

void RPN(string exp)
{
    stackOperations st ;
    int len = exp.length();
    st.allocate(len);
    for(int i=0; i <=len; i++){
        char tmp ;
        tmp = exp[i];
        if(tmp=='('){
            st.push('(');
        }
        else if(tmp==')'){
            char y = st.pop();
            while(y != '('){
                cout << y ;
                y = st.pop();
                }
            }
        else if(int(tmp) >= 97 && int(tmp) <= 122 ) {
            cout << tmp ;   
        }
        else {
            st.push(tmp);
        }

    }
    st.deallocate();
}

int main() {
    int test ;
    string exp ;
    cin >> test;
    cin.ignore();
    while(test!=0){
        getline(cin, exp);
        RPN(exp);
        cout << endl ;
        test--;
    }
    return 0;
}

最佳答案

class stackOperations{
    private:
          int top = -1 ;
          char *arr;
     public:
      void allocate(int len){
           arr = new char[len] ;
  }

关于c++ - 无法从类内的其他函数访问同一类的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47955279/

相关文章:

c++ - 使用 boost json_parser 需要指导

c++ - 如何在一个属性中动态存储基本类型?

php - 在类中定义属性时使用 OR 运算符

python - 优化类模拟代码?

c - OpenSSL 将现有分配的数组清零

c - 如何使用malloc或其他函数在Ram中分配所需的地址?

可变长度的字符

c++ - 将 Node.js 缓冲区传递给 C++ 插件

c++ - 设置 union 不起作用

java - 在类构建过程中使用 setter 的缺点?