zoukankan      html  css  js  c++  java
  • How do I declare and use a pointer to a class member function?

    How do I declare and use a pointer to a class member function? (top)

    The syntax is similar to a regular function pointer, but you also have to specify the class name. Use the .* and ->* operators to call the function pointed to by the pointer.
    Collapse

    class CMyClass
    {
    public:
      int AddOne ( unsigned n ) { return n+1; }
      int AddTwo ( unsigned n ) { return n+2; }
    };
    main()
    {
         CMyClass myclass, *pMyclass = &myclass;
         int (CMyClass::* pMethod1)(unsigned);    // Full declaration syntax
         pMethod1 = CMyClass::AddOne;           // sets pMethod1 to the address of AddOne
         cout << (myclass.*pMethod1)( 100 );    // calls myclass.AddOne(100);
         cout << (pMyclass->*pMethod1)( 200 );  // calls pMyclass->AddOne(200);
         pMethod1 = CMyClass::AddTwo;           // sets pMethod1 to the address of AddTwo
         cout << (myclass.*pMethod1)( 300 );    // calls myclass.AddTwo(300);
         cout << (pMyclass->*pMethod1)( 400 );  // calls pMyclass->AddTwo(400);

        //Typedef a name for the function pointer type.
        typedef int (CMyClass::* CMyClass_fn_ptr)(unsigned); 
        CMyClass_fn_ptr pMethod2;
        // Use pMethod2 just like pMethod1 above....
    }

    The line Collapse
    int (CMyClass::* pMethod1)(unsigned);
    pMethod1 is a pointer to a function in CMyClass; that function takes an unsigned parameter and returns an int.

    Note that CMyClass::AddOne is very different from CMyClass::AddOne(). The first is the address of the AddOne method in CMyClass, while the second actually calls the method.

  • 相关阅读:
    MySQL用户权限管理
    索引 聚集索引 唯一索引 普通索引 联合索引 覆盖索引
    sql注入
    pymysql
    MySQL 多表查询
    MySQL 聚合函数以及 优先级
    mysql 语句 字段 和结构主键外键的增删改
    协程
    事件 event
    进程池和线程池 concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
  • 原文地址:https://www.cnblogs.com/tianfu/p/1706526.html
Copyright © 2011-2022 走看看