【问题标题】:push_back a pointer to a vector of pointerspush_back 指向指针向量的指针
【发布时间】:2018-09-10 01:50:39
【问题描述】:

我有两个班级:ItemBox。在Box.h 我有:

class Box {
  vector<const Item *> BoxItems;

   public:
   void AddItem(const Item *i);
}

Box.cpp:

void Box::AddItem(const Item *i) {
  BoxItems.push_back(*i);
}

仅供参考,但在main.cpp

box.AddItem(&items[0]);

问题:当我编译时,我得到了error: no matching member function for call to 'push_back',它引用了我在Box.h 中创建的向量中的push_back我错过了什么?

到目前为止,我已经尝试过:

void Box::AddItem(const Item *i) {
  this -> BoxItems.push_back(*i);
  Box::BoxItems.push_back(*i);
  BoxItems->push_back(*i);
}

但仍然有同样的错误。

【问题讨论】:

  • push_back(i);
  • 为什么要取消引用指针?

标签: c++ pointers vector


【解决方案1】:
void Box::AddItem(const Item *i) {
  BoxItems.push_back(*i);
}

当它应该使用指向Item 的指针时,您使用Item 调用push_back。将*i 更改为i

但是,我强烈建议不要使用指针向量,因为它很难获得正确的对象所有权。相反,请考虑使用对象向量、unique_ptrs 到对象的向量或 shared_ptrs 到对象的向量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    相关资源
    最近更新 更多