代码之家  ›  专栏  ›  技术社区  ›  kirill_igum jfriend00

c++调用另一类函数的类函数

  •  -2
  • kirill_igum jfriend00  · 技术社区  · 14 年前

    我希望这对你有意义,我搞糊涂了。如果有更简单的方法,请告诉我:

    double A::a(double(b::*bb)())
    {
      b.init();
      return (b->*bb)();
    }
    
    void A::run();
    {
      cout<< a(b.b1);
      cout<< a(b.b2);
    }
    
    class A
    {
      B b;
      void run();
      double a(double(b::*bb)());
    };
    
    class B
    {
      void init();
      double b1();
      double b2();
    };
    
    2 回复  |  直到 14 年前
        1
  •  1
  •   Yakov Galka    14 年前

    这没道理。不过,这是有道理的:

    class B // <- class B definition comes first
    {
      void init();
      double b1();
      double b2();
    };
    
    class A
    {
      B b;
      void run();
      double a(double(B::*bb)()); // <- B instead of b
    };
    
    double A::a(double(B::*bb)()) // <- B instead of b
    {
      b.init();
      return (b->*bb)();
    }
    
    void A::run() // <- you can't put semicolon here
    {
      cout<< a(&B::b1); // <- you want to pass the address of a member.
      cout<< a(&B::b2); // <- you want to pass the address of a member.
    }
    

    现在对我来说更有意义了。

        2
  •  0
  •   John Zwinck    14 年前

    这:

    double a(double(b::*bb)());
    

    应该是:

    double a(double(B::*bb)());
    

    也就是说, bb 将声明为类中成员函数的指针 B ,不在对象中 b (这是一个实例,而不是类型本身,因此不能是类型的一部分)。