尝试将元素推入向量 [英] Trying to push an element in to a vector
问题描述
在一个头文件(我没有写),一个结构已经定义如下
struct MemoryMessage: public boost :: counted_base {/ *,public FastAlloc * /
显式MemoryMessage(MemoryMessageType aType)
:theType(aType){}
显式MemoryMessage(MemoryMessageType aType,MemoryAddress anAddress)
:aType(aType){}
显式MemoryMessage(MemoryMessageType aType,MemoryAddress anAddress,int anIdentifier)
:theType(aType){}
explicit MemoryMessage(MemoryMessageType aType,MemoryAddress anAddress,VirtualMemoryAddress aPC )
:aType(aType){}
显式MemoryMessage(MemoryMessageType aType,MemoryAddress anAddress,VirtualMemoryAddress aPC,DataWord aData)
: & aMsg)
:theType(aMsg.theType){}
}
稍后在我的代码中,我写了
MemoryMessage testMsg;
class foo(){
foo()
:testMsg(MemoryMessage :: test)
{}
std :: vector< MemoryMessage>候选人;
void bar(){
candidates.push_back(testMsg);
}
}
但我收到此错误
错误:没有匹配的函数调用'MemoryMessage :: MemoryMessage(const MemoryMessage&)'
注意:候选者是:MemoryMessage :: MemoryMessage (MemoryMessage&)
这有什么问题?我创建了一个非常小的代码段。
此行背后的行调用一个复制构造函数:
candidates.push_back(testMsg);
从复制构造函数中删除 In a header file (which I haven't written), a struct has been defined like this Later in my code, I have written But I get this error What is wrong with that? I created a very small snippet. Please let me know if I missed something in my explanation. This line behind the scene invokes a copy constructor: The Removing 这篇关于尝试将元素推入向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! testMsg
> std :: vector $>中的复制构造函数将
const
引用放入向量中c $ c>的代码。但是,你的构造函数声明为 explicit
,所以 std :: vector
的代码不能访问它。
显式
指示符将解决此问题。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&)
candidates.push_back(testMsg);
testMsg
that push_back
takes by const
reference is placed into the vector by invoking a copy constructor inside std::vector
's code. However, your constructor is declared explicit
, so std::vector
's code cannot access it.explicit
designator from the copy constructor will fix this problem.