具有受保护成员的自定义对象的排序向量
Sorting vector of custom object with protected members
我正在尝试排序具有派生类对象的向量,其中基类具有受保护的成员
在我的头中,我有基类:
class Item{
protected:
int ID;
string name;
int cost;
int sell;
int profit;
float profitperh;
int time; // in seconds!
vector<string> usedFor;
public:
//getters
//setters
//functions
virtual bool DescProfit (const Item& i1, const Item& i2) const;
bool operator < (const Item& i1) const;
}
从基类中我派生了几个对象,我目前正在使用的对象,看看它是否工作正常,它被命名为Seed,看起来像这样:
class Seed : public Item{
private:
public:
//Constructors
virtual bool operator < (const Item& i1) const{
return (profit < i1.Item::profit); // Also tried this line with i1.Item::profit and i1.Item::getProfit() and i1.Item::profit
}
// virtual bool DescProfit (const Item& i1, const Item& i2) const{
// return i1.profit > i2.profit; // Also tried this line with i1.Item::profit and i1.Item::getProfit() and i1.Item::profit
// } //end DescProfit
当我尝试构建这个时,它在返回行上抱怨'profit'是'Item'的受保护成员操作符<</strong>和DescProfit与sort()配合使用,对vector对象进行排序:
vector<Item*> v1;
sort(v1.begin(), v1.end(), DescProfit);
我试图将bool函数放置在类的内部和外部,上面提到了相同的错误。有人知道这个错误是什么吗?我从这篇文章中得到了上面代码的"模板":对自定义对象向量进行排序我需要做些什么才能访问基类中的受保护变量?
提前谢谢
像<
这样的二元操作符和多态类层次结构不能很好地协同工作。
即使在Item
中声明operator<
是虚的,并在Seed
中重写它,另一个参数仍然是Item
。覆盖的比较运算符可以使用this
对象的Seed
属性,但只能使用另一个对象的Item
属性,因为不知道另一个对象是否为Seed
。
这使得定义一个像它应该那样工作的虚拟<
(反对称,与>
和==
一致,并且不违反LSP) 实际上是不可能的。
这在任何语言中都是正确的,没有特定于c++或vector。有些语言提供多重分派,表面上解决了这个问题。然而,多分派是一个封闭的解决方案(需要预先了解层次结构中的所有类),而普通的OO是开放的。如果您可以接受封闭世界的解决方案,那么您也可以在c++中进行多重分派。
最好的做法是使用一个不需要覆盖的非虚拟<
。
有一种方法可以通过使用成员指针来访问父类受保护的成员(这可能是类型系统中的一个漏洞)
class Seed : public Item {
public:
virtual bool operator < (const Item& i1) const {
int Item::*profitptr = &Seed::profit;
return (profit < i1.*profitptr);
}
}
但是,除非非常必要,否则不建议使用。我建议您重新设计您的体系结构,这样您就可以避免这种情况。
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 对象接收堆栈溢出异常 c++ 的排序向量
- 如何使用 STL 排序对具有模板专用化的自定义类对象进行排序?
- 排序谓词没有传递对索引对象的引用?
- 使用指针指向对象C++对向量进行排序
- 按类成员的顺序对包含类对象的C++向量进行排序
- 无法使用接口类型对priority_queue中的对象进行排序<T>
- 基于不同字段的对象向量的排序功能
- 基于3个对象的自定义排序
- 尝试使用比较运算符对对象向量进行排序
- C++排序的对象集
- 从文件中读取并将其内容放入对象数组中,然后对它们进行排序
- q排序类对象的列表
- std::atexit 从全局对象的构造函数调用时的排序
- 尝试对对象数组进行排序时程序终止
- std::排序为排序自定义对象时出现的向量引发错误
- 通过其char键对对象指针的C 向量进行排序
- 排序算法,使用模板按内部数据对对象进行排序
- 在对象向量中的对象字段排序
- 如何使用 std::sort 对数组中的特定对象进行排序