简体   繁体   中英

automatic conversion using a constructor

I have these 2 classes:

     class iterator {
     public:
            Node<K,V>* n;
            iterator():n(NULL){}
            iterator(const iterator& iter):n(iter.n){}
            explicit iterator(Node<K,V>* nodePtr):n(nodePtr) {}
            void operator=(const iterator& iter);
            void operator++();
            Node<K,V>& operator*();
            bool operator!=(const iterator& iter);
            K& operator[](const Key& k)const;
            V& operator[](const Val& v)const;
    };
    //----const_iterator-class---------------------------


    class const_iterator : public iterator {
    public:
            const Node<K,V>* n;
            const_iterator():n(NULL);
            const_iterator(const const_iterator& iter):n(iter.n){}
            const_iterator(const iterator& iter):n(iter.n){}
            explicit const_iterator(const Node<K,V>* node):n(node){}
            void operator=(const const_iterator& iter){
                    n=iter.n;
            }
            void operator++(){
                    n = n->next;
            }
    };

I want to automatically convert iterator to const_iterator in case a method gets the wrong type as a parameter. I'm trying to use:

 const_iterator(iterator& iter):n(iter.n){}

why do I get a segmentation fault when trying to access what's inside iter.n (the value pointed by n) after it is converted from iterator to const_iterator?

m.begin() and .end may return a temporary?

So what you need is

class const_iterator {
public:
    const_iterator(const iterator &iter) {}
};

Here is code to demonstrate such conversion:

#include <iostream>

class iterator {
     public:
        iterator() { i = -1; }
        int i;
        void bar() const { std::cout << "iterator::bar() " << i << std::endl; }
};

class const_iterator : public iterator {
public:
        const_iterator(int ii) : i(ii) {}
        const_iterator(const iterator &it) : i(it.i) {}
        const int i;
        void bar() const { std::cout << "const_iterator::bar() " << i << std::endl; }
};

void foo(const const_iterator &it) {
        it.bar();
}

int main() {
        iterator it;
        it.i = 777;
        foo(it);
        return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM