您好,这是 this previous question i did 的更新
我试图通过类内的指针执行函数(类内容与我遇到的问题无关)。
这是在上一个问题上发布的代码:
错误信息:
cannot convert ‘Clip::func’ from type ‘void (Clip::)(std::string) {aka void (Clip::)(std::basic_string<char>)}’ to type ‘callback {aka void (*)(std::basic_string<char>)}’
剪辑.h
void func(string str){
cout << str << endl;
}
剪辑.cpp
void Clip::update(){
typedef void(*callback)(string);
callback callbackFunction = func;
callbackFunction("called");
}
------我找到的解决方案------
我和一个 friend 进行了一些快速研究,以找到解决这种情况的方法,这就是我们的发现。尽管这有效,但我们对所涉及的表达式有一些疑问(帖子末尾的问题)
剪辑.h
typedef void (Clip::*Callback) (string);
void func(string _val);
剪辑.cpp
void Clip::update(){
Callback function;
function = &Clip::func;
(this->*function)("a");
}
问题:
a- 在上一篇文章中@tkausl 回答说:“...成员函数指针与(非成员)函数指针不兼容”。这就是为什么其他代码在任何类中都不起作用(即使该类完全是空的)的原因吗?
b- 如果我们已经在 Clip 类中,为什么还需要声明像 thi: Clip::*Callback 这样的指针?
c- 这个表达式是什么意思?:this->*function
d- 对于同样的要求,是否有更简单的方法或表达方式?
提前致谢。
最佳答案
你确实遇到过pointers to member functions .它们与普通函数指针相似,但更细微差别,因为(非静态)成员函数总是隐含地有一个特殊的 this
参数传递给它们,该参数引用当前调用函数的对象。根据包含该函数的类,那个 secret 的 this
参数是强类型的。这就是类名也是指向成员函数类型的指针的一部分的原因。这也是它们不与常规函数指针混合的原因。这是一个基本示例:
// Declaration of a pointer to member function
// Note that no object is used here
void (ClassName::*my_fn_pointer)(ParameterTypes);
// Assignment also doesn't use an object
my_pointer = &ClassName::exampleMemberFunction;
// But to invoke the method, you need an object
ClassName obj;
(obj::*my_fn_pointer)(example_params);
// Alternatively, inside a member function of ClassName:
(this->*my_fn_pointer)(example_params);
有很多选择。我看不到您的其余代码以及您要解决的问题,因此我的建议很有限。然而,我会赞同使用 std::function
与 lambdas :
// std::function generically wraps a callable type
std::function<void(ParamTypes)> my_fn;
// Using an object:
ClassName obj;
// lambda declaration
my_fn = [&obj](ParamTypes params){
// 'obj' is captured by reference, so make sure it stays alive as long as needed
obj.chooseYourMemberFunctionHere(params);
};
// function is called here, syntax is easier on the eyes
my_fn(example_params);
// Using 'this' inside a member function:
my_fn = [this](ParamTypes params){
// 'this' is captured by reference
// also make sure the current object stays alive alive as long as needed
this->chooseYourMemberFunctionHere(params);
};
my_fn(example_params); // function is called here
关于c++ - 指向类成员函数的指针类型转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51388173/