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.

  • 相关阅读:
    Java 理论与实践: 正确使用 Volatile 变量
    VS2005 C++,断点无法命中的解决办法
    IndexWriterConfig的各个配置项说明(转)
    LINQ&Entity Framework
    CDN
    德鲁克之沟通的四原则
    项目管理过程之项目团队
    OOAD & OOP
    双线接入(全网路由)简单介绍
    唐僧为什么可以领导孙悟空
  • 原文地址:https://www.cnblogs.com/tianfu/p/1706526.html
Copyright © 2011-2022 走看看