正确重载从 std::vector 派生的类的双等号

Properly overload double equals for a class deriving from std::vector

本文关键字:派生 vector 重载 std      更新时间:2023-10-16

我有一个类

class Item {
    int _one;
    int _two;
    int _three;
    // other stuff
};
class ItemList : public std::vector<Item> {
    // deriving from std vector because the ctor needs to
    // perform some work in discriminating what gets added
    // to the list
};

我已经阅读了许多反对从 std::vector 派生的论点<>我想我会没事的,因为这个类不是派生的。 我在 python 中公开它,使用 boost 矢量索引套件,充当 python 列表。 因为我需要构造函数在构造过程中做一些工作来从列表中删除某些元素,所以我决定走这条路,而不是做我在项目其他地方做过的事情:

class AnotherItem {
    // class definition
};
typedef std::vector<AnotherItem> AnotherItemList

然后使用 typedef 使用提升矢量索引套件公开列表。 一切似乎都很好,除了我有这个错误:错误 2 错误 C2678:二进制"==":找不到采用类型为"Item"的左侧操作数的运算符(或者没有可接受的转换)

错误不是来自提升库,而是来自 std 算法代码中的某些内容。 我尝试添加我自己的类重载 == 运算符,但这并没有解决问题。 它看起来像这样:

class Item {
    // earlier stuff
    bool operator==(Item& rhs) {
        return (_one == rhs._one && _two == rhs._two && _three == rhs._three);
    }
    bool operator!=(Item& rhs) {
        return !(*this == rhs);
    }
};

这尚未解决问题。 我错过了什么? 此处的此链接显示向量的 == 运算符不是成员函数。 我尝试在"全局"级别(即不在命名空间内)重载,但这也没有帮助。 那么,我错过了什么?

谢谢安 迪

== 的正确重载是

class Item
{
    ...
    bool operator==(const Item& rhs) const
    { .... }
    bool operator!=(const Item& rhs) const
    { return !(*this==rhs); }
};

另外,请注意,由于std::vector没有虚拟成员,因此派生ItelmList不能针对std::vector本身进行多态使用,特别是不要针对 std::vector* 调用 delete。

必须这么说,因为否则我和你将被C++社区所注定,尽管在 30+ 年的编程经验中,我从未见过 std::vector * 或 std::string*。(因此,我真的不知道关于派生性病类的所有"恐惧"是关于:简单地知道你在做什么,让其他人知道)