我'm trying to write class similar to std::vector, which would contain an Iterator as inner class. For some member functions of Iterator I would like to access variables from my Vector class. For example when overloading operator++ I would like to check if index of Iterator doesn' t超过Vector的大小(如果是这样的话,抛出std :: out_of_range()) . 我已经基于this topic实现了对外部类变量的访问 . 但由于某些原因,编译器向我抛出以下错误:
错误C2440:'':无法从'初始化列表'转换为'Vector :: Iterator'
这是我的代码的最小版本复制问题:
template <typename Type>
class Vector
{
public:
class Iterator;
Vector() : size(0), capacity(0), data(nullptr) {}
Iterator begin()
{
return Iterator(this, 0);
}
private:
size_t size, capacity;
Type* data;
};
template <typename Type>
class Vector<Type>::Iterator
{
public:
Iterator(Vector& vectorRef, size_t index) : vectorRef(vectorRef), index(index) {}
private:
size_t index;
Vector& vectorRef;
};
int main()
{
Vector<int> vec;
vec.begin();
return 0;
}
这是什么原因?将引用传递给Vector类是否有意义?或者,还有更好的方法?
1 回答
这是因为
this
的类型为Vector*
或const Vector*
,但您的构造函数正在接受Vector&
,因此找不到匹配的构造函数 .试试
Vector(*this, 0)
.