(C++) 无法从我的堆栈对象调用 push() 和 pop()

(C++) unable to call push() and pop() from my stack object

为什么我无法使用堆栈的 push() 和 pop() 函数调用?以下是错误:

HCTree.cpp:65:16: error: no matching member function for call to 'push'
  encoding.push(0);
  ~~~~~~~~~^~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/stack:197:10: note: 
  candidate function not viable: 'this' argument has type 'const stack<int,
  std::vector<int> >', but method is not marked const
void push(value_type&& __v) {c.push_back(_VSTD::move(__v));}
     ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/stack:194:10: note: 
  candidate function not viable: 'this' argument has type 'const stack<int,
  std::vector<int> >', but method is not marked const
void push(const value_type& __v) {c.push_back(__v);}
     ^
HCTree.cpp:67:16: error: no matching member function for call to 'push'
  encoding.push(1);
  ~~~~~~~~~^~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/stack:197:10: note: 
  candidate function not viable: 'this' argument has type 'const stack<int,
  std::vector<int> >', but method is not marked const
void push(value_type&& __v) {c.push_back(_VSTD::move(__v));}
     ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/stack:194:10: note: 
  candidate function not viable: 'this' argument has type 'const stack<int,
  std::vector<int> >', but method is not marked const
void push(const value_type& __v) {c.push_back(__v);}
     ^
HCTree.cpp:73:16: error: member function 'pop' not viable: 'this' argument has type 'const
  stack<int, std::vector<int> >', but function is not marked const
  out.writeBit(encoding.pop());
           ^~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/stack:206:10: note: 
  'pop' declared here
void pop() {c.pop_back();}
     ^

代码:

void HCTree::encode(byte symbol, BitOutputStream& out) const
{

  HCNode* temp;
  temp = leaves[symbol];//store leaf node containing symbol into temp
  /* traverse to the top of the tree */
  while(temp->p != NULL)
  {
    /* record path we take to parent into a stack */
    if(temp == temp->p->c0)//if temp is the c0 child
      encoding.push(0);
    else//temp is the c1 child
      encoding.push(1);

    temp = temp->p;//move up to temp's parent and repeat
  }

   /* write bits to buffer */
   out.writeBit(encoding.pop());


}

来自HCTree.hpp的相关行:

    stack<int,std::vector<int>> encoding;

是否有关于使用向量阻止我使用 push() 和 pop() 函数调用的问题?

您使用限定符 const

声明了成员函数
void HCTree::encode(byte symbol, BitOutputStream& out) const
                                                       ^^^^^

这意味着您不能更改对象的数据成员。编译器对此有说明。

如果堆栈被声明为可变的,您可以更改堆栈。