它们的意义何在?
我从来没有用过它们,而且我认为自己根本不需要使用它们。
我是不是遗漏了一些关于它们的信息,还是它们几乎没用?
编辑:我对它们了解不多,所以可能需要对它们进行描述......
最佳答案
PMF(指向成员函数的指针)类似于普通(静态)函数指针,除了因为非静态成员函数需要指定 this
对象,所以 PMF 调用语法 (.*
或 ->*
) 允许指定 this
对象(在左侧)。
这是一个使用 PMF 的例子(注意使用 .*
运算符的“魔法”行:(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)
。空格是可选的,但可以添加以提高可读性。
关于c++ - 将指针绑定(bind)到 C++ 中的成员运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/746604/