繁体   English   中英

在指向不同类的指针的向量中找到一个类

[英]Find a class in vector of pointers to different classes

所以我有这个:

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 &);
}

我想实现删除功能。 我尝试了这个:

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++;

}
}

但是==不会返回我真实的值。 我还尝试在每个形状上重载运算符==,但结果相同。 我能做什么?

这是比较两个Shape对象的内存地址:

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

它没有比较两个Shape对象。 需要进一步取消引用以使用为Shape定义的operator== 但是,请参见对类层次结构重载operator ==的正确方法是什么? 有关如何处理类层次结构的operator==的讨论。

您正在比较形状指针的地址,但它们是不同的。

您应该重载运算符==

这里有些例子:

C ++运算符重载准则

运算符重载

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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