【问题标题】:Equal operator: pointer to a member function等号运算符:指向成员函数的指针
【发布时间】:2013-11-15 14:06:07
【问题描述】:

在我的一个类中,我包含了一个指向成员函数的指针:

private:
void (class_name::*_pf)(double&, gc::mag::coefficient&, gc::mag::st&, const int&) const;

此指针指向 function1function2class_name

现在,当我有两个 class_name 类的对象时,如何检查 _pf 指针是否指向同一个成员函数(即它们都指向 function1function2)?

【问题讨论】:

  • 虽然 C++ 肯定会允许您使用这种方法,但听起来有一个带有虚拟成员的基类,您可以从该基类派生两个实现这两种类型函数的其他类将是更好的方法。现代 C++ 的用法是远离直接使用指针,因为它是缺陷的来源。这听起来像是会成为缺陷来源的棘手代码。
  • 当您有两个函数指针时,您可以简单地将它们与if (_pf1 == _pf2) 进行比较。请注意,这完全独立于 class_name 类的任何实例。

标签: c++ pointers


【解决方案1】:

这就够了:

if (this->_pf == other._pf)

例子:

#include <iostream>

class class_name
{
  public:
  void function1(int) {}
  void function2(int) {}
};

class test
{
    public:
    test(void (class_name::*pf)(int))
    : _pf(pf)
    {
    }

    bool operator==(const test& other)
    {
        return (this->_pf == other._pf);
    }

  public:
    void (class_name::*_pf)(int);
};

int main()
{
   test t(&class_name::function1);
   test t2(&class_name::function2);

   std::cout << std::boolalpha << (t == t2) << std::endl;

   return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多