我不能做一个简单的仿函数来比较字符串

sin*_*ge3 -1 c++ std functor

我有这个仿函数类:

#include <string>

using namespace std;

class IsPlayerOfType
{
    public:
        IsPlayerOfType(const string& type) : type_(type) {}

        bool operator()(const Player* player) const
        {
            return (player->getType() == type_);
        }
    private:
        string type_;
};
Run Code Online (Sandbox Code Playgroud)

"Player"类表示具有多种方法和属性的玩家.其中,有getType()方法返回一个字符串.

在我的程序的某些时候,我有一个名为players_type 的变量vector<Player*>

最后,我有以下代码来计算我的向量中某种类型的玩家数量:

int number = count_if(players_.begin(), players_.end(), IsPlayerOfType("Defensive"));
Run Code Online (Sandbox Code Playgroud)

编译时我遇到很多错误,例如:

  • 错误C2011:'IsPlayerOfType':'class'类型重定义
  • 错误C2440:'':无法从'const char [10]'转换为'IsPlayerOfType'
  • 错误C2780:'iterator_traits <_Iter> :: difference_type std :: count_if(_InIt,_InIt,_Pr)':需要3个参数 - 提供2个参数

    我不太了解count_if是如何工作的,我试着写这段代码从这个答案中激励自己:https://stackoverflow.com/a/13525420

    我没有看到我错在哪里,编译器错误让我感到困惑.

Mar*_*k B 5

我的通灵调试技巧告诉我你忘了#define标题中的包含守卫,它定义了IsPlayerOfType导致标题在一些源文件中被多次包含.请记住,#include预处理器的工作是进行文本替换,这意味着预处理器需要额外的逻辑来尝试防止多次包含.

另请注意,using标头中的文件范围非常危险,应该避免.