【问题标题】:Iterator copy constructor error, illegal as right side '.' operator迭代器复制构造函数错误,作为右侧“。”是非法的操作员
【发布时间】:2014-07-22 13:12:19
【问题描述】:

检查this 的答案后,我似乎仍然无法解决我的问题:

我目前有一个test_iterator 结构,它将不同类型的迭代器标签包装到它上面,允许我使用所有类型的迭代器测试函数。当为这个迭代器创建一个复制构造函数时,我的问题就出现了。当前结构定义为

template <typename BaseIterator, typename IteratorTag>
struct test_iterator
  : boost::iterator_adaptor<
        test_iterator<BaseIterator, IteratorTag>,
        BaseIterator, boost::use_default, IteratorTag>
{
private:
    typedef boost::iterator_adaptor<
        test_iterator<BaseIterator, IteratorTag>,
        BaseIterator, boost::use_default, IteratorTag>
    base_type;

public:
    test_iterator() : base_type() {}
    test_iterator(BaseIterator base) : base_type(base) {};

    test_iterator(const test_iterator& cpy): 
        base_type(cpy.base_type) {};
};

最后一个构造函数(复制构造函数)给我带来了麻烦,我似乎无法理解我做错了什么。我收到的确切错误是

error C2274: 'function-style cast' : illegal as right side of '.' operator

这是这一行:

base_type(cpy.base_type) {};

【问题讨论】:

  • 您是在测试函数中的代码还是迭代器?
  • 您没有接受函数对象的构造函数。你确定你说的不是 base_type(cpy.base_type()) 吗?
  • 让编译器隐式定义复制构造函数(以及移动构造函数、析构函数和复制/移动赋值)。

标签: c++ c++11 copy-constructor


【解决方案1】:

. 的右侧不能有类型。您可以使用

test_iterator(const test_iterator& cpy)
    : base_type(static_cast<base_type const&>(cpy)) {}

...或者,鉴于已经指定了基本类型,您可以使用

test_iterator(const test_iterator& cpy)
    : base_type(cpy) {}

【讨论】:

  • 但是请注意,如果base_type 也有一个接受const test_iterator &amp; 的ctor(在这种情况下我可以轻松想象),那么您显示的两种方式会有不同的行为。跨度>
【解决方案2】:

排队

base_type(cpy.base_type) {};

你指的是base_type,它是一个typedef,你想要底层的迭代器。需要调用iterator_adaptor提供的base()方法:

base_type(cpy.base()) {};

【讨论】:

    【解决方案3】:
    test_iterator(const test_iterator& cpy): 
        base_type(cpy.base_type) {};
    

    test_iterator 类没有成员 base_type,但有一个 typedef base_type,所以如果你真的想凭空初始化基础,那就是

    test_iterator(const test_iterator& cpy): 
        base_type(base_type()) {};
    

    但这毫无意义,因为这会产生一个 nullptr 等价物。

    我猜你想实现的是

     test_iterator(const test_iterator& cpy): 
            base_type(/*(const base_type&)*/cpy) {};
    

    这是合法的,因为test_iterator 继承自base_type(我假设 base-type 实际上有一个带有 base_type const& 的复制 ctor);但是那个向下转换是编译器为你做的,所以你不需要手动转换它。


    顺便说一句-我认为这是

    test_iterator(BaseIterator base) : base_type(base) {};
    

    应该是

    test_iterator(const BaseIterator& base) : base_type(base) {};
    

    不应该。

    【讨论】:

      猜你喜欢
      • 2021-12-08
      • 2021-03-27
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      • 1970-01-01
      相关资源
      最近更新 更多