Using a member function pointer within a class

前端 未结 5 693
有刺的猬
有刺的猬 2020-12-28 21:21

Given an example class:

class Fred
{
public:
Fred() 
{
    func = &Fred::fa;
}

void run()
{
     int foo, bar;
     *func(foo,bar);
}

double fa(int x,          


        
5条回答
  •  不知归路
    2020-12-28 22:05

    There are two things you need to take care of. First is the declaration of the function pointer type:

    private:
      typedef double (Fred::*fptr)(int x, int y);
      fptr func;
    

    Next is the syntax for calling the function using a pointer:

    (this->*func)(foo,bar)
    

    Here is the modified sample code that will compile and run:

    #include 
    
    class Fred
    {
    public:
      Fred() 
      {
        func = &Fred::fa;
      }
    
      void run()
      {
        int foo = 10, bar = 20;
        std::cout << (this->*func)(foo,bar) << '\n';
      }
    
      double fa(int x, int y)
      {
        return (double)(x + y);
      }
      double fb(int x, int y)
      {
      }
    
    private:
      typedef double (Fred::*fptr)(int x, int y);
      fptr func;
    };
    
    int
    main ()
    {
      Fred f;
      f.run();
      return 0;
    }
    

提交回复
热议问题