【问题标题】:Variables does not have class type, even though it is defined变量没有类类型,即使它已定义
【发布时间】:2016-07-25 03:12:02
【问题描述】:

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

下面是我写的代码:

#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"));

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

【问题讨论】:

    标签: c++ stdmap most-vexing-parse


    【解决方案1】:

    那行

    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) };
    

    【讨论】:

    • 非常感谢。像魅力一样工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    相关资源
    最近更新 更多