【问题标题】:Return a pointer to class member function返回指向类成员函数的指针
【发布时间】:2013-11-13 18:56:41
【问题描述】:

下面的问题让我抓狂,虽然它看起来并不奇怪:

class Foo;

// This is the location of the first error code
//        ↓
int (Foo::*)(int) getPointer()
{
    return 0;
}

GCC 给我:

error: expected unqualified-id before ')' token
error: expected initializer before 'getPointer'

PS:我用 -std=c++11 编译

【问题讨论】:

  • 看在上帝的份上使用 typedefs
  • @Slava 完全同意,但也很高兴了解它是如何工作的。
  • @Slava 我不能,因为返回类型取决于推导的模板参数,并且您不能在 'template' 和 'getPointer()' 之间进行 typedef

标签: c++ pointers gcc c++11 member-function-pointers


【解决方案1】:
int ( Foo::* ( getPointer() ) )();

话虽如此,请记住您可以使用typedef。对于函数指针,通常会提高整体的可读性:

typedef int ( Foo::* TypeName )();

TypeName getPointer();

【讨论】:

    【解决方案2】:

    使用 typedef,例如:

    class Foo;
    
    typedef int (Foo::*POINTER)(int);
    
    POINTER getPointer()
    {
        return 0;
    }
    

    这里有更多的推理:http://www.parashift.com/c++-faq/typedef-for-ptr-to-memfn.html

    【讨论】:

    • 使用所有大写标识符通常是个坏主意。
    • 这通常取决于贵公司决定采用的编码标准。
    • 对预处理器使用大写标识符似乎不是公司编码标准,而是到处使用。
    【解决方案3】:

    看起来你正在尝试使用函数指针,但没有给它命名:P

    使用这个:

    int (Foo::*myPointer)(int) getPointer()
    {
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-27
      • 2013-06-06
      • 2018-05-22
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多