具有受保护成员的自定义对象的排序向量

Sorting vector of custom object with protected members

本文关键字:对象 排序 向量 自定义 受保护 成员      更新时间:2023-10-16

我正在尝试排序具有派生类对象的向量,其中基类具有受保护的成员

在我的头中,我有基类:

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

但是,除非非常必要,否则不建议使用。我建议您重新设计您的体系结构,这样您就可以避免这种情况。