引用成员函数?

发布于 2024-12-02 03:43:56 字数 399 浏览 2 评论 0原文

我最近发现 C++ 中有一个函数引用的概念:)。 因此存在函数指针和成员函数指针不同的类型。问题出现了。是否有“引用成员函数”的概念?

我尝试编译以下代码,但 GCC 3.4.6 给出错误。

#include <iostream>

using namespace std;

class A {
public:
  virtual void Af() const {
    cout << "A::Af()" << endl;
  }
};

int main() {
  typedef void (A::& MemFnc)() const;
  MemFnc mf = &A::Af;

  A a;
  (a.*mf)();

  return 0;
}

I recently find out that there is a reference-to-function concept in C++ :).
So as there are pointer-to-function and pointer-to-member-function different types. The question arises. Is there a "reference-to-member-function" concept?

I tried to compile the following code, but GCC 3.4.6 gives an error.

#include <iostream>

using namespace std;

class A {
public:
  virtual void Af() const {
    cout << "A::Af()" << endl;
  }
};

int main() {
  typedef void (A::& MemFnc)() const;
  MemFnc mf = &A::Af;

  A a;
  (a.*mf)();

  return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

恬淡成诗 2024-12-09 03:43:56

C++ 中不存在所谓的对成员的引用

语言规范在注释中明确指出(§8.3.3/3 - 2003),

指向成员的指针不得指向类 (9.4) 的静态成员、引用类型的成员或“cv void”。 [注:另见 5.3 和 5.5。 “指向成员的指针”类型与“指针”类型不同,即指向成员的指针仅由指向成员的指针声明符语法声明,而从不由指针声明符语法声明。 C++ 中没有“引用成员”类型。

There is no such a thing called reference to member in C++.

The language specification explicitly says in a note (§8.3.3/3 - 2003) that,

A pointer to member shall not point to a static member of a class (9.4), a member with reference type, or “cv void.” [Note: see also 5.3 and 5.5. The type “pointer to member” is distinct from the type “pointer”, that is, a pointer to member is declared only by the pointer to member declarator syntax, and never by the pointer declarator syntax. There is no “reference-to-member” type in C++.

晚雾 2024-12-09 03:43:56

不,不可能引用成员函数。

从某种意义上说,取消引用指向成员函数的指针的结果可以作为一个结果,但是您可以对该结果执行的唯一操作就是在其上调用函数调用运算符,按照 5.5[expr.mptr.oper]/6。没有其他的事情是允许的。

No, references to member functions are not possible.

In some sense, the result of dereferencing a pointer to a member function could serve as one, but the only thing you can do with that result is to invoke a function call operator on it, per 5.5[expr.mptr.oper]/6. Nothing else is allowed.

时间你老了 2024-12-09 03:43:56

没有对成员函数的引用。

There is no reference to member function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文