11

クラスの例を考えると:

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

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

double fa(int x, int y);
double fb(int x, int y);

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

ポインタ「*func(foo、bar)」を介してメンバー関数を呼び出す行でコンパイラエラーが発生し、「termは2つの引数を取る関数に評価されません」と表示されます。私は何が間違っているのですか?

4

5 に答える 5

22

必要な構文は次のようになります。

((object).*(ptrToMember)) 

したがって、あなたの呼び出しは次のようになります。

((*this).*(func))(foo, bar);

別の構文は次のようになると思います。

(this->*func)(foo, bar);
于 2010-05-24T16:05:13.217 に答える
7

ポインタを介してメンバー関数を呼び出すには、次のファンキーな構文が必要です。

(this->*func)(foo, bar);
于 2010-05-24T16:05:38.383 に答える
6

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 <iostream>

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;
}
于 2010-05-24T16:28:30.303 に答える
1

2つの引数を持つメンバー関数は、実際には3つの引数の関数です。'this'は暗黙の引数であるため、取得するエラーは'this'引数が欠落していることに関するものです。

于 2010-05-24T17:02:03.230 に答える
0

非静的クラス メンバ関数は、このポインタを引数として隠しています。

構文 (this->*func)(foo,bar) は、これを関数に追加する必要があることをコンパイラに理解させる方法だと思います。

于 2010-05-24T16:46:11.483 に答える