在下面的示例中,我需要定义一个函数来使用 getHappiness(Animal*) 方法中的某些规则来比较我的对象。该方法不能是静态的并且相当复杂。我需要比较定义中的指针来调用 getHappiness 方法。
所以我的问题是:如何将指针传递给此方法,当我将元素插入 map 时它会自动调用。而且我似乎无法实例化比较结构并将指针传递给构造函数。
我做错了什么吗?也许我可以用另一种方法来定义比较函数?
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(...);
...
}
最佳答案
您的代码中存在设计问题。 Happiness
应该是属于 animal
而不是 zoo
的属性。所以在 animal
上实现 getHappiness()
可以让你的代码更简单:
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 容器中使用智能指针。
关于c++ - 如何将变量传递给函数对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19172024/