迭代器复制构造函数错误,非法作为右侧'。'操作者

时间:2014-07-21 15:51:07

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

在检查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) {};

3 个答案:

答案 0 :(得分:5)

.右侧无法提供类型。你可以使用

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

...或者,如果已经指定了基本类型,则可以使用

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

答案 1 :(得分:1)

在第

base_type(cpy.base_type) {};

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

base_type(cpy.base()) {};

答案 2 :(得分:0)

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实际上有一个拷贝ctor采用base_type const&amp;);但是那个向下转换是编译器为你做的,所以你不需要手动转换它。


顺便说一句 - 我认为这个

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

应该是

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

不应该。