为什么必须使用address-of运算符获取指向成员函数的指针? [英] Why must I use address-of operator to get a pointer to a member function?

查看:107
本文介绍了为什么必须使用address-of运算符获取指向成员函数的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct A
{
    void f() {}
};

void f() {}

int main()
{
    auto p1 = &f;     // ok
    auto p2 = f;        // ok
    auto p3 = &A::f; // ok

    //
    // error : call to non-static member function
    // without an object argument
    //
    auto p4 = A::f; // Why not ok?
}

为什么必须使用address-of运算符获取指向成员函数的指针?

Why must I use address-of operator to get a pointer to a member function?

推荐答案

auto p1 = &f;     // ok
auto p2 = f;      // ok

第一个或多或少是正确的事情.但是由于非成员函数具有隐式转换指向指针,因此&没必要C ++进行了这种转换,适用于静态成员函数.

The first is more or less the right thing. But because non-member functions have implicit conversions to pointers, the & isn't necessary. C++ makes that conversion, same applies to static member functions.

要引用 cppreference :

函数类型T的左值可以隐式转换为prvalue 指向该函数的指针.这不适用于非静态成员 函数,因为引用非静态成员函数的左值确实 不存在.

An lvalue of function type T can be implicitly converted to a prvalue pointer to that function. This does not apply to non-static member functions because lvalues that refer to non-static member functions do not exist.

这篇关于为什么必须使用address-of运算符获取指向成员函数的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆