2014-10-01 79 views
0

请有人可以帮助解释为什么我在OS X上使用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. 

回答

4

你的构造应const参考采取其参数

X(VectorType const & params) 
      ^^^^^ 

否则,你无法通过临时向量(当你试图去做),因为临时对象不能绑定到非const 左值引用。

+0

非常感谢。我不知道。 – ksl 2014-10-01 15:24:16

3

X具有3层构造:

  • 你的用户定义一个,这抑制了自动默认构造函数:

    X(VectorType& params) 
    
  • 自动复制构造函数和移动-构造函数:

    X(X&&) noexcept 
    X(const X&) 
    

一个期望的左值,从不一个x值或恒定对象定制。
你可能想这样分割的构造函数:

X(const VectorType& params) : m_params(params) {} 
X(VectorType&& params) : m_params(std::move(params)) {}