如何将变量传递给函数对象?

时间:2013-10-04 02:04:13

标签: c++ functor

在下面的考试中,我需要定义一个函数来使用getHappiness(Animal *)方法中的某些规则来比较我的对象。该方法不能是静态的而是相当复杂的。我需要在比较定义中使用指针来调用getHappiness方法。

所以我的问题是:如何将指针传递给此方法,当我将一个元素插入地图时会自动调用它。而且我似乎不能实例化Compare结构并将指针传递给构造函数。

我做错了吗?也许有另一种方法来定义比较函数?

struct Compare {bool operator()(Animal* const, Animal* const) const;}; 

bool
Compare::operator()(Animal* const a1, Animal* const a2) const {

  Zoo* zoo; // somehow I need to get access to the Zoo instance here

  if (zoo->getHappiness(a1) > zoo->getHappiness(a2)) return true;
  return false;
}

Class Zoo(){
  std::multimap<Animal*, Man*, Compare> map;

  int getHappiness(Animal*); // cannot be static

}

int main(){
...
  Zoo zoo;
  zoo.map.insert(...);
...
}

1 个答案:

答案 0 :(得分:1)

您的代码中存在设计问题。 Happiness应该是属于animal而非zoo的属性。因此,在getHappiness()上实施animal会使您的代码更加简单:

struct Compare 
{
    bool operator()(Animal& const, Animal& const) const;
}; 

bool Compare::operator()(Animal& const a1, Animal& const a2) const 
{
    return a1.getHappiness() < a2.getHappiness();
}

Class Zoo(){
  std::multimap<Animal, Man, Compare> map;

}

此外,如果没有必要,请不要使用指针。如果无法避免指针,请在STL容器中使用智能指针。