如何解决这个错误`从const_iterator转换为非标量类型`?

时间:2018-06-05 22:55:22

标签: c++ c++11 vector iterator

有人可以解释这个错误的提及:

  

转换自' std :: vector< int,std :: allocator< int> > :: const_iterator {aka __gnu_cxx :: __ normal_iterator< const int *,std :: vector< int,std :: allocator< int> > >}'到非标量类型' std :: vector< int,std :: allocator< int> > :: iterator {aka __gnu_cxx :: __ normal_iterator< int *,std :: vector< int,std :: allocator< int> > >}'要求

给出以下课程:

#include <vector>
#include <iostream>

using std::vector;
using std::ostream;

template<class T>
class Gen {
    vector<T> array;
public:
    explicit Gen(int size);
    template<class S>
    friend ostream& operator<<(ostream& os, const Gen<S>& g);
};

template<class T>
Gen<T>::Gen(int size) {
    for (int i = 0; i < size; i++) {
        this->array.push_back(T());
    }
}

template<class T>
ostream& operator<<(ostream& os, const Gen<T>& g) {
    for (typename vector<T>::iterator it = g.array.begin(); it != g.array.end();
            it++) { // ****** error ********
        os << *it << " ";
    }
    return os;
}

int main() {
    Gen<int> g(3);
    std::cout << g << std::endl;
}

我该如何解决?

1 个答案:

答案 0 :(得分:3)

您正在将const Gen<T>传递给operator<<。这意味着当你调用g.array.begin()时,你正在调用begin的const重载,它会返回const_iterator

const_iterator begin() const noexcept;

然后您尝试将其分配给vector<T>::iterator,这会导致编译器错误。你可以像这样解决这个问题:

auto it = g.array.begin()

告诉编译器推导出it的正确类型。