正确重载从 std::vector 派生的类的双等号
Properly overload double equals for a class deriving from std::vector
我有一个类
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*。(因此,我真的不知道关于派生性病类的所有"恐惧"是关于:简单地知道你在做什么,让其他人知道)
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中用vector填充一个简单的动态数组
- vector.resize()中的分配错误
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 使用std::vector的OpenCL矩阵乘法
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 在某些循环内使用vector.push_back时出现分段错误
- 在从仅移动类型派生的类中定义析构函数在使用 std::vector emplace_back或push_back创建时会
- 正确重载从 std::vector 派生的类的双等号
- 不能交换从 Vector 派生的类中的结构
- std::vector<> 使用 resize() 派生,它不初始化原语和转发construct_back
- 从 vector<Parent* 中获取派生类对象>
- 将派生类的unique_ptr添加到基类unique_ptr的vector上
- 从Cocos2d::Layer派生的类有一个指针数据成员.这个元素也有一个向量容器.调用vector::push_bac
- 以多态方式使用派生类的std::vector成员的复制赋值会导致内存泄漏
- 需要指导:从抽象基类到派生类的unique_ptr的vector对象
- 如何在使用 std::vector<Base*> 存储派生* 时指定
- 如何正确地将可能派生类shared_pointers添加到 std::vector 中
- vector迭代的派生和基之间的类型转换:C2664错误