变量没有 class 类型,即使它已被定义

Variables does not have class type, even though it is defined

我正在尝试编写一个 class 来定义 std::map。映射的比较器必须是函数指针。函数指针可以作为 class 构造函数中的参数传递给 class。

下面是我写的代码:

#include <iostream>
#include <map>
#include <string>
#include <functional>

typedef std::function<bool(std::string x, std::string y)> StrComparatorFn;

bool FnComparator(std::string x, std::string y) {
  return strtoul(x.c_str(), NULL, 0) < strtoul(y.c_str(), NULL, 0);
}

class MyClass {
 public:
  MyClass(StrComparatorFn fptr):fn_ptr(fptr){};

  void Insert() {
    my_map.insert(std::pair<std::string, std::string>("1", "one"));
    my_map.insert(std::pair<std::string, std::string>("2", "two"));
    my_map.insert(std::pair<std::string, std::string>("10", "ten"));
  }

  void Display() {
    for (auto& it : my_map) {
      std::cout << it.first.c_str() << "\t => " << it.second.c_str() << "\n";
    }
  } 
 private:
  StrComparatorFn fn_ptr;
  std::map<std::string, std::string, StrComparatorFn> my_map(StrComparatorFn(fn_ptr));
};

int main() {
  MyClass c1(&FnComparator);
  c1.Insert();
  c1.Display();
}

我在 Insert 中遇到编译错误:

error: '((MyClass*)this)->MyClass::my_map' does not have class type
 my_map.insert(std::pair<std::string, std::string>("1", "one"));

这个问题有什么解决办法吗?

那一行

std::map<std::string, std::string, StrComparatorFn> my_map(StrComparatorFn(fn_ptr));

有一个问题被称为最令人烦恼的解析。基本上,所有可以解释为函数的东西都是:

Foo f(); //f is a function! Not a variable

在您的例子中,my_map 被解析为没有定义的已声明函数。使用花括号代替曲括号将解决问题,因为列表初始化永远不能被解释为函数:

std::map<std::string, std::string, StrComparatorFn> my_map{ StrComparatorFn(fn_ptr) };