Creating a class member pointer function variable that points to a non-static class member function

﹥>﹥吖頭↗ 提交于 2019-12-05 22:56:25

问题


The goal is to have the member variable _AddValue point to the CreateFirstValue function upon class initialization and after the first invocation of AddValue, all future calls to it will invoke CreateAnotherValue.

Previously, I just had a single AddValue function with a conditional check to determine which function to call. However, I feel like that implementation is flawed because that if check will occur every time and it seems like a function pointer would be beneficial here.

An example:

class Foo
{
 private:
  int _value;
  void (*_AddValue)(int value); // Pointer to function member variable

  void CreateFirstValue(int value)
  {
    _value = value;
    _AddValue = &CreateAnotherValue;
  }

  void CreateAnotherValue(int value)
  {
    // This function will create values differently.
    _value = ...;
  }

 public:
  // Constructor
  Foo()
   : _value(0), _AddValue(CreateFirstValue)
  {
  }

  AddValue(int value) // This function is called by the user.
  {
    _AddValue(value);
  }
};

The code above is not the actual code, just an example of what I'm trying to accomplish.

right now I'm getting an error: argument of type void (BTree::)(int) does not match void (*)(int)


回答1:


&CreateAnotherValue

This syntax is not valid. To create a pointer-to-member, you have to name the class, even from inside other members. Try

&Foo::CreateAnotherValue

In this case you are talking the address of a qualified non-static member function, which is allowed and prevents the error about address of unqualified member function.

Of course, you then need an appropriately typed variable to store the pointer-to-member in, see Bo's answer for the correct declaration. When it comes time to call it, you will need to use the pointer-to-member-dereference operator (either .* or ->*), so say

(this->*_AddValue)(whatever);

The same rule applies to data, if you say &Foo::_value, you get a pointer-to-member of type int Foo::*. But in the data case, the unqualified name is also accepted, but with very different behavior. &_value gives a normal pointer, type int*, which is the address of the specific _value member variable inside the this instance.




回答2:


  void (*_AddValue)(int value); // Pointer to function member variable

This is not really a pointer-to-member, but a pointer to a free function.

You need to make this

void (Foo::*_AddValue)(int value); // Pointer to function member variable


来源:https://stackoverflow.com/questions/11057206/creating-a-class-member-pointer-function-variable-that-points-to-a-non-static-cl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!