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

时间:2010-11-28 01:57:28

标签: c++ class function pointers

我希望这对你有意义,我感到困惑。如果有更简单的方法,请告诉我:

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 个答案:

答案 0 :(得分:1)

没有意义。这有道理:

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.
}

现在对我来说更有意义。

答案 1 :(得分:0)

此:

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

应该是:

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

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