简体   繁体   中英

How to cast std::vector<myClass*> to std::vector<const myClass* const>?

I have a std::vector<myClass*> member of a class I would like to give public const-access to in the class interface. To do this I want to be able to write:

    class myClass{
        public: 
        myClass() { /*allocate dynamic stuff */};
        virtual ~myClass() { /* delete dynamic stuff */};

        //Accessors
        const std::vector<const myClass * const> members() const{ //<- How do I implement?

            //Compiles Fine - cit iterates over   const int*    objects
            std::vector<myClass*>::iterator it =  _members.begin(); 

            //Does not compile
            std::vector<myClass* const>::const_iterator citc= it;

            //I need citc to iterate over     cosnt int* const     objects - How?
            std::vector<const myClass * const> members_(citc, citc + _members.size());  //Compile Error

            return members_;
        };  
        /* ...moar stuff....*/
        private:
        /* ...moar stuff...*/
        std::vector<myClass*> _members;
    };

This code was a cleaned example out of context so I have not compiled it, but in the actual code, I deduced from a couple screen lengths of error messages that the only serious problem was that i need the citc iterator to iterate over 'const myClass* const' objects rather than 'const myClass*' objects. Thoughts? Thanks a mil.

return std::vector<myClass const *>( _members.begin(), _members.end() ); 

And remove that one const from your return value (the 2nd one in the <> s). It does nothing but get in the way.

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