You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何自定义map类的成员m_hasher不存在?编译报错求解

问题根源:typedef语法错误导致类型别名无效

你遇到的编译错误,核心原因是你的typedef写法完全错了——它没有定义你想要的函数类型别名,反而声明了一个名为func的函数,导致类里的const func m_hasher; 是一个无效的成员声明,编译器根本识别不出m_hasher的类型,所以报错说这个字段不存在。

具体分析你的typedef问题

你写的这行代码:

typedef int (& func(const std::string &));

在C++中,这不是定义类型别名,而是声明了一个名为func的函数:这个函数接受const std::string&参数,返回int&类型的引用。完全不是你想要的“哈希函数类型”的别名。

修正方案

你需要调整typedef的语法,来正确定义函数指针或函数引用的类型别名:

方案1:使用函数指针(更常用、灵活)

如果你想把哈希函数作为指针存储,正确的typedef写法是:

typedef int (*func)(const std::string&);

然后修正你的类代码:

typedef int (*func)(const std::string&);

template <class t_child>
class map final {
    std::vector<t_child> m_table;
    const func m_hasher; // 现在func是有效的函数指针类型
public:
    explicit map(func hasher) : m_hasher(hasher) {}
    map(const map &copy) = delete;
    ~map() = default; // 如果你没有自定义析构逻辑,可以显式默认
    map &operator=(const map&) = delete;
    // 其他成员...
};

方案2:使用函数引用(必须在初始化列表绑定,不可更改)

如果你坚持用函数引用,正确的typedef写法是:

typedef int (&func)(const std::string&);

对应的类代码:

typedef int (&func)(const std::string&);

template <class t_child>
class map final {
    std::vector<t_child> m_table;
    func m_hasher; // 函数引用类型的成员(引用一旦绑定就不能更改)
public:
    explicit map(func hasher) : m_hasher(hasher) {} // 必须在这里初始化引用
    map(const map &copy) = delete;
    ~map() = default;
    map &operator=(const map&) = delete;
    // 其他成员...
};

为什么这样写是对的?

C++的typedef语法要求你把类型别名放在“变量名”的位置。比如定义函数指针别名时,int (*func)(const std::string&) 可以理解为:如果func是一个变量,它是一个指向“接受const string&、返回int的函数”的指针——typedef之后,func就变成了这种指针类型的别名。

内容的提问来源于stack exchange,提问作者Denis Steinman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:28:40