【发布时间】:2014-08-19 23:21:08
【问题描述】:
扩展我之前的post,我不明白,为什么这段代码会失败。这里没有明确的说明。
#include <vector>
class foo {
public:
int num;
int type;
foo()
: num(0)
, type(0)
{}
foo(foo &a)
: num(a.num)
, type(a.type)
{}
};
int main()
{
foo theFoo;
theFoo.num = 10;
theFoo.type = 2;
std::vector< foo > theVec;
theVec.push_back(theFoo);
return 0;
}
错误是
no matching function for call to ‘foo::foo(const foo&)’
mytest.cpp:12: note: candidates are: foo::foo(foo&)
mytest.cpp:8: note: foo::foo()
有人可以清楚地解释这里出了什么问题吗?
【问题讨论】:
-
将
foo(foo &a)更改为foo(const foo &a)。 “真正的”复制构造函数采用const引用。 -
该错误与我在链接中得到的相同。罪魁祸首是
explicit。现在为什么我会得到同样的错误? -
错误信息应该有多明确?只是阅读它...
-
@Deduplicator:他的意思是
explicit关键字,我猜... -
@quantdev:我知道,但我没有将它用作那里的关键字。
标签: c++ vector copy-constructor