代码之家  ›  专栏  ›  技术社区  ›  AlastairG

如何重写要与类指针一起使用的运算符?

c++
  •  0
  • AlastairG  · 技术社区  · 6 年前

    假设我有:

    class A {
        public:
            operator ==(int int_val) { return (m_int_val == int_val); }
    
        private:
            int m_int_val;
    };
    

    我可以这样做:

    bool my_func(const A &a) { return (a == 42); }
    

    甚至:

    bool my_func(const A *a) { return ((*a) == 42); }
    

    到现在为止,一直都还不错。但假设我有:

    std::list<A *> a_list;
    

    auto it = std::find(a_list.begin(), a_list.end(), 42);
    

    我的问题不是如何解决这个问题 std::find_if (只是为了先发制人)。我的问题是,我能为指向的指针定义一个等价运算符吗 std::find

    当我寻求更好地理解C++时,我会问。

    2 回复  |  直到 6 年前
        1
  •  5
  •   Holt 111111    6 年前

    你的运算符等于重载

    operator==(A const&, int);
    

    所以你想让这个超负荷:

    operator==(A const*, int);
    

    但是 you cannot 重载运算符,除非其参数之一具有用户定义的类型和指向任何类型的指针(例如。, A const* )不是用户定义的。

    std::find_if 而不是 std::find

    auto it = std::find_if(std::begin(a_list), std::end(a_list),
                           [](auto const* pa) { return *pa == 42; });
    

    你真的超载了 operator==(A&, int) 因为你没有 const bool operator==(int int_val) const { ... } ).

    对于这种运算符,通常重载非成员函数而不是成员函数。