【问题标题】:Trying to push an element in to a vector试图将元素推入向量
【发布时间】:2014-06-29 09:14:23
【问题描述】:

在一个头文件(我没有写)中,已经定义了一个这样的结构

struct MemoryMessage : public boost::counted_base { /*, public FastAlloc*/
  explicit MemoryMessage(MemoryMessageType aType)
   : theType(aType) {}
  explicit MemoryMessage(MemoryMessageType aType, MemoryAddress anAddress)
   : theType(aType) {}
  explicit MemoryMessage(MemoryMessageType aType, MemoryAddress anAddress, int anIdentifier)
   : theType(aType) {}
  explicit MemoryMessage(MemoryMessageType aType, MemoryAddress anAddress, VirtualMemoryAddress aPC)
   : theType(aType) {}
  explicit MemoryMessage(MemoryMessageType aType, MemoryAddress anAddress, VirtualMemoryAddress aPC, DataWord aData)
   : theType(aType) {}
  explicit MemoryMessage(MemoryMessage & aMsg)
   : theType(aMsg.theType) {} 
}

在我的代码后面,我写了

MemoryMessage testMsg;
class foo() {
  foo()
   : testMsg(MemoryMessage::test)
  {}
  std::vector< MemoryMessage > candidates;

  void bar() {
     candidates.push_back(testMsg);   
  }
}

但我得到了这个错误

error: no matching function for call to 'MemoryMessage::MemoryMessage(const MemoryMessage&)’
note: candidates are:MemoryMessage::MemoryMessage(MemoryMessage&)

这有什么问题?我创建了一个非常小的 sn-p。如果我在解释中遗漏了什么,请告诉我。

【问题讨论】:

  • 将 explicit MemoryMessage(MemoryMessage &amp; aMsg) 更改为 MemoryMessage(const MemoryMessage &amp; aMsg)
  • 再次检查错误信息,并将编译器查找的内容与您的复制构造函数进行比较。
  • @Dieter Lücking:没错。但我需要为我编写的代码(三行)提供一个解决方案。我不想更改explicit 部分
  • 尝试.emplace_back 而不是.push_back。
  • 你使用的是什么 C++ 编译器?

标签: c++ vector stl explicit


【解决方案1】:

幕后的这一行调用了一个复制构造函数:

candidates.push_back(testMsg);   

通过在std::vector 的代码中调用复制构造函数,将push_back 引用的const 引用的testMsg 放入向量中。但是,您的构造函数声明为explicit,因此std::vector 的代码无法访问它。

从复制构造函数中删除 explicit 指示符将解决此问题。

【讨论】:

  • 不,我不想删除explicit,因为它是许多其他事情的核心。我写的三行能做什么?
  • @mahmood 显式复制构造函数几乎没有任何意义,尤其是在所有其他构造函数都标记为显式的情况下。
  • @Joachim Pileborg:您确定将explicit MemoryMessage(MemoryMessage &amp; aMsg) 更改为MemoryMessage(MemoryMessage &amp; aMsg) 并保持其他内容不变可以修复错误吗?
  • @mahmood This 是复制构造函数的签名。所以你需要它来获取const &amp;。您也可以简单地将其留给编译器并要求默认构造函数,如果这足够好的话。
  • 虽然删除显式将修复错误,但我仍在寻找另一种保持显式并可以将元素推回向量的解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-03
相关资源
最近更新 更多