我正在写一个自己的容器类,并遇到了一个问题,我不能得到我的头。这是显示问题的裸骨样本。自己的容器类的C++迭代器和const_iterator问题
它由一个容器类和两个测试类组成:一个测试类使用std:vector很好地编译,第二个测试类尝试以完全相同的方式使用我自己的容器类,但很难编译。
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
template <typename T>
class MyContainer
{
public:
class iterator
{
public:
typedef iterator self_type;
inline iterator() { }
};
class const_iterator
{
public:
typedef const_iterator self_type;
inline const_iterator() { }
};
iterator begin() {
return iterator();
}
const_iterator begin() const {
return const_iterator();
}
};
// This one compiles ok, using std::vector
class TestClassVector
{
public:
void test() {
vector<int>::const_iterator I=myc.begin();
}
private:
vector<int> myc;
};
// this one fails to compile. Why?
class TestClassMyContainer
{
public:
void test(){
MyContainer<int>::const_iterator I=myc.begin();
}
private:
MyContainer<int> myc;
};
int main(int argc, char ** argv)
{
return 0;
}
GCC告诉我:
test2.C: In member function ‘void TestClassMyContainer::test()’:
test2.C:51: error: conversion from ‘MyContainer::iterator’ to non-scalar type ‘MyContainer::const_iterator’ requested
我不知道在哪里,以及为什么编译器要迭代器转换为常量性为我自己的类,但不是为STL向量类。我究竟做错了什么?
非常感谢。现在我只需要看看我是否声明const_iterator是迭代器的朋友......或者将访问函数写入私有迭代器成员,但这应该是可行的。 – BaCh 2010-05-16 16:20:50