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

Ran*_*nks 1 c++ stack vector

为什么我无法使用堆栈的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();}
     ^
Run Code Online (Sandbox Code Playgroud)

代码:

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());


}
Run Code Online (Sandbox Code Playgroud)

来自HCTree.hpp的相关内容:

    stack<int,std::vector<int>> encoding;
Run Code Online (Sandbox Code Playgroud)

有没有关于使用向量阻止我使用push()和pop()函数调用的东西?

Vla*_*cow 5

您使用限定符声明了成员函数 const

void HCTree::encode(byte symbol, BitOutputStream& out) const
                                                       ^^^^^
Run Code Online (Sandbox Code Playgroud)

这意味着您可能无法更改对象的数据成员.并且编译器说了这个.

如果它被声明为可变,您可以更改堆栈.