首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在构造对向量时出现编译器错误

在构造对向量时出现编译器错误
EN

Stack Overflow用户
提问于 2014-10-01 14:56:32
回答 2查看 1.4K关注 0票数 0

请有人解释一下为什么我在OS上使用Xcode 5.1编译以下代码时出错。Apple LLVM版本5.1 (clang-503.0.40) (基于LLVM 3.4svn)。

我要在下面构造X,给它传递成对的向量。

代码语言:javascript
复制
#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;
}

报告的错误是:

代码语言:javascript
复制
/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.
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-10-01 15:02:57

构造函数应该以const引用作为其参数。

代码语言:javascript
复制
X(VectorType const & params)
             ^^^^^

否则,您就不能传递一个临时向量(就像您尝试的那样),因为临时变量不能绑定到非const值引用。

票数 4
EN

Stack Overflow用户

发布于 2014-10-01 15:01:09

X有3个构造函数:

  • 您的用户定义的一个,它禁止自动默认ctor: X(向量型&仿射)
  • 自动复印机和移动机: X( X&) no除X(const X&)

自定义需要一个lvalue,而不是xvalue或常量对象。

您可能希望这样拆分ctor:

代码语言:javascript
复制
X(const VectorType& params) : m_params(params) {}
X(VectorType&& params) : m_params(std::move(params)) {}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26144299

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档