English 中文(简体)
在班级内使用成员职能协调人
原标题:Using a member function pointer within a class

举例说:

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)”运作,他说:“定期不评价一项有2个论点的职能”。 我做了什么错误?

最佳回答

你们需要的是:

((object).*(ptrToMember)) 

因此,你呼吁:

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

我认为,另一个国家是:

(this->*func)(foo, bar);
问题回答

您需要以下金yn,通过点子来召集成员的职能:

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

你们需要照顾两件事。 第一是宣布职能单位类型:

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

接下来是使用点子来指定该功能的星号:

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

下面是经过修改的样本代码,将汇编和操作:

#include <iostream>

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

  void run()
  {
    int foo = 10, bar = 20;
    std::cout << (this->*func)(foo,bar) <<  
 ;
  }

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

非固定阶层成员的职能掩盖了这个论点。

I think, the syntax (this->*func)(foo,bar) is the way to make compiler understand that it need to add this to the function.

拥有两个动力的成员职能实际上是三个动力职能。 这是一种暗含的论点,因此,你正在发现的错误是失去了这一动力。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签