我有一个类 (Uniform),它有一个带 2 个参数的构造函数和一个默认的复制构造函数(它只包含 int、 float 、一个 std::vector 和一个 std::map)。我创建了一个
std::vector<Uniform> uniforms
我想用
uniforms.push_back()
行。我使用这段代码来做到这一点(第二行只是在这里测试复制构造函数,因为它目前失败了)
Uniform uni(uniform_name,type);
Uniform uni2=uni;
uniforms.push_back(uni2);
默认构造函数工作正常,“uni2=uni”编译没有问题(因此默认复制构造函数也可以),但 push_back 返回(使用 g++ 作为编译器):
/usr/lib/gcc/x86_64-unknown-linux-gnu/4.6.0/../../../../include/c++/4.6.0/ext/new_allocator.h:108:9: erreur: no matching function for call to ‘Uniform::Uniform(const Uniform&)’
/usr/lib/gcc/x86_64-unknown-linux-gnu/4.6.0/../../../../include/c++/4.6.0/ext/new_allocator.h:108:9: note: candidates are:
./inc/uniform.h:16:5: note: Uniform::Uniform(std::string, Uniform_Type)
./inc/uniform.h:16:5: note: candidate expects 2 arguments, 1 provided
./inc/uniform.h:14:7: note: Uniform::Uniform(Uniform&)
./inc/uniform.h:14:7: note: no known conversion for argument 1 from ‘const Uniform’ to ‘Uniform&’
谢谢:)
最佳答案
当您说“默认复制构造函数”(这通常没什么意义)时,我假设您指的是“隐式声明的复制构造函数”或“编译器提供的复制构造函数”
编译器提供的复制构造函数的确切签名将取决于您的 Uniform
类的内容。它可以是 Uniform::Uniform(const Uniform &)
或 Uniform::Uniform(Uniform &)
再次取决于 Uniform
的细节>(您没有提供)。
例如,如果您的 Uniform
包含类型为 T
的子对象(基类或成员),其复制构造函数声明为 T::T(T &)
(没有const
),那么Uniform
的隐式构造函数也会被隐式声明为Uniform::Uniform(Uniform &)
(无 const
)。
可以在语言标准 (12.8/5) 中找到完整的规范
The implicitly-declared copy constructor for a class X will have the form
X::X(const X&)
if
— each direct or virtual base class B of X has a copy constructor whose first parameter is of type const B& or const volatile B&, and
— for all the nonstatic data members of X that are of a class type M (or array thereof), each such class type has a copy constructor whose first parameter is of type const M& or const volatile M&.
Otherwise, the implicitly declared copy constructor will have the form
X::X(X&)
An implicitly-declared copy constructor is an inline public member of its class.
push_back
实现需要 Uniform::Uniform(const Uniform &)
,但是你的类中的某些东西导致它成为 Uniform::Uniform(Uniform & )
。因此错误。如果没有看到 Uniform
的定义,就无法说出它是什么。
关于C++ vector::push_back 使用默认拷贝构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6310638/