2009-04-14 42 views
4

它们的含义是什么?
我从来没有使用过任何东西,我也看不到我自己需要使用它们。
我错过了一些关于他们的东西,还是他们几乎没用?

编辑:我不很了解他们,所以关于他们的描述可能是必要的......在C++中绑定指向成员操作符的指针

+0

是http://stackoverflow.com/questions/654853/why-would-one-use-function-pointers-to-member-method-in-c你在找什么? – nevets1219 2009-04-14 07:01:37

+0

不,更具体地说,。*和 - > *运算符。 – DeadHead 2009-04-14 07:05:41

+0

我怀疑不是,我想他是在谈论指向成员操作员的指针(例如operator +) – 2009-04-14 07:05:58

回答

10

甲PMF(成员函数指针)是像一个正常的(静态)函数指针,除了,因为非静态成员函数所需要的this对象被指定,PMF调用语法(.*->*)允许指定this对象(在左侧)。

这里的(正在使用注意与.*操作者的 “魔力” 行:(lhs.*opit->second)(...),以及用于创建PMF,&class::func语法):在使用保偏光纤的一个例子

#include <complex> 
#include <iostream> 
#include <map> 
#include <stack> 
#include <stdexcept> 
#include <string> 

namespace { 
    using std::cin; using std::complex; using std::cout; 
    using std::invalid_argument; using std::map; using std::stack; 
    using std::string; using std::underflow_error; 

    typedef complex<double> complexd; 
    typedef complexd& (complexd::*complexd_pmf)(complexd const&); 
    typedef map<char, complexd_pmf> opmap; 

    template <typename T> 
    typename T::reference top(T& st) { 
     if (st.empty()) 
      throw underflow_error("Empty stack"); 
     return st.top(); 
    } 
} 

int 
main() 
{ 
    opmap const ops{{'+', &complexd::operator+=}, 
        {'-', &complexd::operator-=}, 
        {'*', &complexd::operator*=}, 
        {'/', &complexd::operator/=}}; 

    char op; 
    complexd val; 
    stack<complexd> st; 

    while (cin >> op) { 
     opmap::const_iterator opit(ops.find(op)); 
     if (opit != ops.end()) { 
      complexd rhs(top(st)); 
      st.pop(); 
             // For example of ->* syntax: 
      complexd& lhs(top(st));  // complexd* lhs(&top(st)); 
      (lhs.*opit->second)(rhs); // (lhs->*opit->second)(rhs); 
      cout << lhs << '\n';  // cout << *lhs << '\n'; 
     } else if (cin.unget() && cin >> val) { 
      st.push(val); 
     } else { 
      throw invalid_argument(string("Unknown operator ") += op); 
     } 
    } 
} 

[Download]

这是一个简单的RPN计算器,它使用复数而不是实数(主要是因为std::complex是带有重载运算符的类类型)。我用clang测试了这个;您的里程可能会因其他平台而异。

输入的格式应该是(0,1)。空格是可选的,但可以添加以提高可读性。

4

绑定指向一个功能是在各种情况下非常有用的。基本上,它允许您将函数作为变量来引用,这使您可以在运行时选择要调用的函数。

一个用于此的是“回调”。假设我想让一些后台进程工作一段时间,并告诉我们什么时候完成(所以我们可以更新GUI或其他)。但有时候,我们可能希望这个后台进程调用一个方法,有时我们希望它调用一个不同的方法。我们可以编写它,而不是编写这个后台进程的两个版本,以便后台进程接收一个指向我们希望它“回调”的函数的指针。然后,当这个过程完成时,它会首先调用它提供的功能。

基本上,它只是让你有一个更灵活的决定调用哪种方法。这样就和多态性非常相似。事实上,在幕后,我相信C++使用函数指针来促进多态性(通过为每个类存储指向函数的不同指针表)

1

如果我正确理解你的问题。为什么不?

struct test 
{ 
    test* operator->() 
    { 
     std::cout << "test::operator->"; 
     return this; 
    } 
}; 

test tt; 
boost::bind(&test::operator ->, _1)(tt);