【问题标题】:c++ call class's function of another class's functionc++调用另一个类的函数的类的函数
【发布时间】:2010-11-28 01:57:28
【问题描述】:

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

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();
};

【问题讨论】:

  • 你的问题到底是什么?
  • 这没有意义.. bb 是什么?您是否收到错误消息?可以发一下吗?
  • 你这样做的真正目的是什么?
  • 顺便说一句,B::init 应该是B::B; C++ 有真正的构造函数。

标签: c++ class function pointers


【解决方案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.
}

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

【讨论】:

    【解决方案2】:

    这个:

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

    应该是:

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

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

    【讨论】:

      猜你喜欢
      • 2012-12-19
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多