gpt4 book ai didi

c++ - 如何修复此错误 `conversion from const_iterator to non-scalar type`?

转载 作者:搜寻专家 更新时间:2023-10-31 00:26:57 26 4
gpt4 key购买 nike

谁能解释一下这个错误是什么意思:

conversion from 'std::vector<int, std::allocator<int> >::const_iterator {aka __gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >}' to non-scalar type 'std::vector<int, std::allocator<int> >::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >}' requested

给出以下类:

#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;
}

我该如何解决?

最佳答案

您正在传递 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 推断出正确的类型.

关于c++ - 如何修复此错误 `conversion from const_iterator to non-scalar type`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50710023/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com