请有人解释一下为什么我在OS上使用Xcode 5.1编译以下代码时出错。Apple LLVM版本5.1 (clang-503.0.40) (基于LLVM 3.4svn)。
我要在下面构造X,给它传递成对的向量。
#include <iostream>
#include <string>
#include <vector>
#include <utility>
struct X
{
public:
typedef std::vector<std::pair<std::string, std::string>> VectorType;
X(VectorType& params) : m_params(params)
{
}
VectorType m_params;
};
int main(int argc, const char * argv[])
{
X::VectorType pairs
{
{ "param-1", "some-string-1"}, // pair 0
{ "param-2", "some-string-2"}, // pair 1
{ "param-3", "some-string-3"}, // pair 2
{ "param-4", "some-string-4"}, // pair 3
{ "param-5", "some-string-5"}, // pair 4
{ "param-6", "some-string-6"}, // pair 5
{ "param-7", "some-string-7"} // pair 6
};
X x
{
{pairs[0], pairs[2], pairs[5]}
};
return 0;
}报告的错误是:
/main.cpp:37:7: error: no matching constructor for initialization of 'X'
X x
^
/main.cpp:6:8: note: candidate constructor (the implicit move constructor) not viable: cannot convert initializer list argument to 'X'
struct X
^
/main.cpp:6:8: note: candidate constructor (the implicit copy constructor) not viable: cannot convert initializer list argument to 'const X'
struct X
^
/main.cpp:11:5: note: candidate constructor not viable: cannot convert initializer list argument to 'VectorType &' (aka 'vector<std::pair<std::string, std::string> > &')
X(VectorType& params) : m_params(params)
^
1 error generated.发布于 2014-10-01 15:02:57
构造函数应该以const引用作为其参数。
X(VectorType const & params)
^^^^^否则,您就不能传递一个临时向量(就像您尝试的那样),因为临时变量不能绑定到非const值引用。
发布于 2014-10-01 15:01:09
X有3个构造函数:
自定义需要一个lvalue,而不是xvalue或常量对象。
您可能希望这样拆分ctor:
X(const VectorType& params) : m_params(params) {}
X(VectorType&& params) : m_params(std::move(params)) {}https://stackoverflow.com/questions/26144299
复制相似问题