简体   繁体   中英

Find a class in vector of pointers to different classes

So i have this:

class Grup : public Shape
{
private:
    std::vector<Shape *> continut;
public:
    static const std::string identifier;
    Grup(){};
    ~Grup(){
    continut.clear();
    };
    void add(Shape *);
    void remove(Shape *);
    void output(std::ostream &) const;
    void readFrom(std::istream &);
    void moveBy(int, int);
    friend std::ostream &operator<<(std::ostream &, const Grup &);
}

and i want to implement the remove function. i tried this:

void Grup::remove(Shape *s)
{
vector<Shape*>::iterator it;
it = continut.begin();
while(it!=continut.end())
{
    if((*it) == s)
    {
    it = continut.erase(it);
    }
    else it++;

}
}

but the == doesn't return me a true value. i also tried to overload the operator == on each shape but same result. what can i do?

This is comparing the memory addresses of two Shape objects:

if((*it) == s) // '*it' is of type `Shape*`

it is not comparing two Shape objects. A further dereference is required to use operator== defined for Shape . However, see What's the right way to overload operator== for a class hierarchy? for a discussion on how to handle operator== for a class hierarchy.

you are comparing the shape pointers addresses and they are different.

you should overload operator ==

here are some examples:

C++ Operator Overloading Guidelines

Operator overloading

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