C 中的成员指针运算符 ->\* 和 .\* 是什么?

新手上路,请多包涵

是的,我已经看过 这个问题这个常见问题解答,但我 仍然 不明白 ->*.* 在 C++ 中的含义。

这些页面提供 了有关 运算符的信息(例如重载),但似乎没有很好地解释它们 什么。

What are ->* and .* in C++, and when do you need to use them as compared to -> and . ?

原文由 user541686 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 513
1 个回答

我希望这个例子能为你清除一切

//we have a class
struct X
{
   void f() {}
   void g() {}
};

typedef void (X::*pointer)();
//ok, let's take a pointer and assign f to it.
pointer somePointer = &X::f;
//now I want to call somePointer. But for that, I need an object
X x;
//now I call the member function on x like this
(x.*somePointer)(); //will call x.f()
//now, suppose x is not an object but a pointer to object
X* px = new X;
//I want to call the memfun pointer on px. I use ->*
(px ->* somePointer)(); //will call px->f();

现在,您不能使用 x.somePointer()px->somePointer() 因为在类 X 中没有这样的成员。为此,使用了特殊的成员函数指针调用语法……只需尝试自己举几个例子,你会习惯的

原文由 Armen Tsirunyan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题