【问题标题】:Find a class in vector of pointers to different classes在指向不同类的指针向量中找到一个类
【发布时间】:2013-04-07 14:42:02
【问题描述】:

所以我有这个:

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

}
}

但是 == 并没有给我返回一个真正的价值。我还尝试在每个形状上重载运算符 == 但结果相同。我该怎么办?

【问题讨论】:

  • 只有两个建议,使用std::remove 而不是while(为什么要键入已经在 stl 上键入的算法?)并且不要清除析构函数中的向量,它将是反正清除了。
  • 发布你的代码重载 operator== 不起作用
  • @makc 我试过这样的事情:bool Triunghi::operator==(const Triunghi&amp; T) { if(this-&gt;identifier==T.identifier&amp;&amp;this- &gt;p1.getX()==T.p1.getX()&amp;&amp;this-&gt;p1.getY()==T.p1.getY()&amp;&amp;this-&gt;p2.getX()==T.p2.getX()&amp;&amp;this-&gt;p2.getY()==T.p2.getY()&amp;&amp;this-&gt;p3.getX()==T.p3.getX()&amp;&amp;this-&gt;p3.getY()==T.p3.getY()) return 1; return 0; }
  • @user2116010 标识符代表什么?您是否尝试调试此代码并检查哪个参数不相等?
  • @makc 是的,我试过了,它甚至没有进入这个重载函数

标签: c++ oop operator-overloading


【解决方案1】:

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

你应该重载 operator ==

这里有一些例子:

C++ Operator Overloading Guidelines

Operator overloading

【讨论】:

    【解决方案2】:

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

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

    它不是比较两个Shape 对象。需要进一步取消引用才能使用为Shape 定义的operator==。但是,请参阅 What's the right way to overload operator== for a class hierarchy?,了解有关如何处理类层次结构的 operator== 的讨论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多