开发者

Problem with conversion

I have a class:

      template<class T>
        class MyClass
        {
        public:
                class Iterator {
    public:
    Iterator(MyClass<T>&){/*some code*/};
    };


  operator Iterator();
    Iterator& begin();
        };

    template<c开发者_如何学Pythonlass T>
    MyClass<T>::operator typename MyClass<T>::Iterator()
    {
        return MyClass::Iterator(*this);
    }

    template<class T>
    typename MyClass<T>::Iterator& MyClass<T>::begin()
    {
        return *this;//<---------------cannot convert from MyClass to MyClass<T>::Iterator
    }

Why am I getting an error? I've provided conversion operator so everything should be fine.


begin() cannot return a reference to an Iterator; it needs to return an Iterator by value.

When the user-declared conversion to Iterator is called, it yields a temporary Iterator object. A non-const reference cannot be bound to a temporary, hence the error you get when begin() returns a reference.

That said, having a conversion function that returns an Iterator is unusual at best.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜