复制构造函数错误示例
copy constructor error with example
延伸我之前的帖子,我不明白,为什么这段代码失败了。这里没有显式语句
#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()
谁能清楚地解释一下这里出了什么问题? 错误信息足够清晰。在声明
theVec.push_back(theFoo);
类std::vector push_back
中有一个已使用的成员函数,在类中以如下方式声明
void push_back(const T& x);
如您所见,形参被定义为const引用。要将对象x复制到容器中对象的类型必须将复制构造函数声明为
T( const T & );
或者在你的情况下
foo( const foo &a );
但是你的类没有这样的构造函数。所以编译器发出错误
相关文章:
- "error: no matching function for call to"构造函数错误
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 模板,函数使用错误的构造函数来复制我的对象
- C++ OpenCV 卡尔曼滤波器构造函数错误
- 不命名构造函数和析构函数上的类型错误
- 处理简单 cpp 类构造函数中的错误
- 类和构造函数中的函数根本不起作用,并且不返回任何错误
- 链接器错误:无法解析构造函数
- 当我尝试通过构造函数分配 char 数组时出现错误
- 没有参数的构造函数给我错误
- 使用复制构造函数的程序输出错误
- 默认构造函数上的分段错误
- 错误: 无效使用非静态数据成员"应用程序::应用程序构造函数"
- 为什么定义复制构造函数会给我错误:无法将类型 'obj&' 的非常量左值引用绑定到类型为"obj"的右值?
- 带有 QWidget 的分段错误构造函数.Qt/C++
- C++错误构造函数参数
- 错误:构造函数未命名类型
- 错误:构造函数在此上下文中受到保护
- 没有匹配的函数错误C++构造函数
- 错误:构造函数的多个定义