修改接口列表中的类的属性

问题描述 投票:0回答:0

在我工作的项目中,有一个名为 schedule 的类实现了一个名为 ValidateShiftForDay 的函数:

bool Schedule::ValidateShiftForDay(Entities::Employee &employee, Entities::Shift &currentShift, int day, bool fromMutation)
{

    std::list<std::string>::iterator itContract;

    std::unordered_map<std::string, Entities::Contract> Contracts =
        Helpers::Variables::getInstance().getContracts();
    bool shiftOk;
    std::list<std::string> IdContracts = employee.GetContracts();
    int multiplier = fromMutation ? 0 : 1;
    for(std::string IdContract: IdContracts)
    {
        Entities::Contract& contract = Contracts.at(IdContract);
        if (contract.IsValidShift(currentShift.GetId()))
        {
            shiftOk = contract.ValidateRules(*this, currentShift, day, employee.GetId(), multiplier);
            if (!shiftOk)
            {
                return false;
            }
        }
    }
    return true;
}

还有一个类叫做Contract。在这个类中,有一个接口列表

class Contract {
 public:
    Contract(std::string Id);
    bool ValidateRules(Schedule &schedule, 
        Shift shift, int day,std::string IdEmployee, int multiplier = 1);

 private:

    std::list<Constraints::IConstrainable*> Rules;
    void UpdateCurrentValue(Schedule &schedule, Shift shift,
                               int day, std::string IdEmployee, int multiplier);
    
};

这里我们有 ValidateRules 的实现


  bool Contract::ValidateRules(Schedule &schedule, Shift shift,
                               int day, std::string IdEmployee, int multiplier)
  {
    for (Constraints::IConstrainable *constraint : this->Rules)
    {
      if (!constraint->CheckConstraint(schedule, shift, day, IdEmployee, multiplier))
      {
        return false;
      }
    }

    UpdateCurrentValue(schedule, shift, day, IdEmployee, multiplier);
    return true;
  }

几个类实现了 IConstrainable 接口,例如类 Workload。 Workload 实现 UpdateCurrentValue 如下:

    void Workload::UpdateCurrentValue(Schedule &schedule, Entities::Shift shift,
                                         int day, std::string IdEmployee, int multiplier)
    {
        
        if (multiplier == 1)
        {
            currentWorkload = currentWorkload + shift.GetDuration();
        }
    }

每次运行这个方法,currentWorkload都会增加,但是下次运行这个方法,currentWorkload的值又是0了

为什么currentWorkload总是0?正如您所想象的那样,currentWorkload 是类 Workload 的私有属性。

c++ pointers reference
© www.soinside.com 2019 - 2024. All rights reserved.