C++ 具有受保护成员的自定义对象的排序向量
我试图对具有派生类对象的向量进行排序,其中基类具有受保护的成员 在我的标题中,我有基类:C++ 具有受保护成员的自定义对象的排序向量,c++,sorting,object,vector,C++,Sorting,Object,Vector,我试图对具有派生类对象的向量进行排序,其中基类具有受保护的成员 在我的标题中,我有基类: class Item{ protected: int ID; string name; int cost; int sell; int profit; float profitperh; int time; // in seconds! vector<string> usedFor; public:
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”的受保护成员
运算符二进制运算符,如AFAIK有一种方法可以通过使用成员指针访问受父类保护的成员这可能是类型系统中的漏洞
class Seed : public Item {
public:
virtual bool operator < (const Item& i1) const {
int Item::*profitptr = &Seed::profit;
return (profit < i1.*profitptr);
}
}
但是,除非非常必要,否则不建议这样做。我建议您重新设计您的体系结构,以避免这种情况。您的矢量是项目指针,而不是项目。默认情况下,根本不会调用比较器。无论如何,该操作符都应该在基类中定义。您提供的链接问题中没有对象指针。你可以打赌,事情会有所不同,你会赢的。你声明一个指向项的指针向量,然后尝试用一个谓词对它进行排序,该谓词接受一个项而不是指向项的指针。这只是一个建议。使用函数对象和重载操作符来实现可扩展性。我使用的是虚拟多态性,比较器就是这样根据派生函数的类型调用。我在这篇文章中试图删除它,但显然未能删除main.vsoftco中的指针-当我将不同类型的派生类推送到向量中时,您建议如何更改它?在运行时使用typeid检查它是否属于该类型如何?这样行吗?Typeid不好有很多原因。在基础架构代码中使用它是可以的,但在业务代码中它破坏了LSP,应该避免。如果必须检查动态类型,请选择动态类型转换。不管怎样,它都不能解决这个问题,因为你可以用种子和种子来比较这两种情况,你必须使这两种情况保持一致。这是我的一个私人项目-但非常感谢你的帮助:明天要为它重新设计谢谢,我会想办法让它在基类中成为非虚拟的,这也是n.m.在上面的回答中建议的:
class Seed : public Item {
public:
virtual bool operator < (const Item& i1) const {
int Item::*profitptr = &Seed::profit;
return (profit < i1.*profitptr);
}
}