尝试从抽象类创建子类时遇到问题

class people
{
public:
   people();
   ~people();
   virtual int comparable(people*);
   void order(people**,int);
};


我的子类

class worker : public people
{
private:
  int salary;
public:
  worker();
  ~worker();
  int comparable (people*);
};


我需要按薪水(从工人)订购一个动态的人数组,但是我无法匹配一个人数组[j] = worker a;

你有什么建议?
然后我怎么称呼功能指令?因为无法创建人员对象

最佳答案

提供一个纯虚函数来比较两个people

#include <algorithm>
#include <utility>
#include <stdexcept>

class people
{
   public:
      people();
      ~people();
      virtual int compare(const people* rhs) const = 0;
};


compare中实现worker功能。

class worker : public people
{
   private:
      int salary;
   public:
      worker();
      ~worker();
      virtual int compare(const people* rhs) const
      {
         const worker* rhsw = dynamic_cast<const worker*>(rhs);
         if ( NULL == rhsw )
         {
            throw std::invalid_argument("rhs");
         }
         return (this->salary - rhsw->salary);
      }
};


提供可以在std::sort中使用的函子。

struct people_compare
{
   bool operator()(people* lhs, people* rhs) const
   {
      return (lhs->compare(rhs) < 0);
   }
};


使用std::sort和上面的函子对人员列表进行排序。

void order(people** plist, int num)
{
   std::sort(plist, plist+num, people_compare());
}

10-07 13:19