创建指向非静态类成员函数的类成员指针函数变量 [英] Creating a class member pointer function variable that points to a non-static class member function
问题描述
目标是让成员变量 _AddValue
在类初始化时和第一次初始化后指向 CreateFirstValue
函数调用 AddValue
,将来对其进行的所有调用都会调用 CreateAnotherValue
。
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
.
以前,我只有一个 AddValue
函数,并通过条件检查来确定要调用的函数。但是,我觉得这种实现是有缺陷的,因为 if
检查每次都会发生,并且似乎函数指针在这里会很有用。
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.
示例:
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.
现在我遇到了一个错误: void(BTree ::)(int)类型的参数与void(*)( int)
right now I'm getting an error: argument of type void (BTree::)(int) does not match void (*)(int)
推荐答案
&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.
当然,您需要一个适当类型的变量来存储指向成员的指针,请参见Bo的答案为正确的声明。需要调用它时,您将需要使用指向成员取消引用的指针运算符(。*
或->>
),这样说
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);
同一规则适用于数据,如果您说& Foo :: _value
,您将得到一个指向 int Foo :: *
类型的成员的指针。但是在数据情况下,也可以接受非限定名称,但行为却大不相同。 & _value
给出普通指针,键入 int *
,这是特定此
实例中的> _value 成员变量。
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.
这篇关于创建指向非静态类成员函数的类成员指针函数变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!