![](/img/trans.png)
[英]C++: passing the template callback method into the other method: cannot convert ‘<unresolved overloaded function type> to pointer
[英]Error: cannot convert '<unresolved overloaded function type>' to 'function pointer'
#include<iostream>
#include<bitset>
#include<string.h>
#include<string>
#include<vector>
#include<math.h>
#include<stdarg.h>
class b {
public:
b();
void ef(void(*f)());
};
class d : public b{
public:
d();
void print();
};
b::b() {}
void b::ef(void(*f)()) { f(); }
d::d(): b(){}
void d::print() { cout<<"WORKS"<<endl; }
int main() {
d obj;
obj.ef(obj.print);
}
我有一个派生的 class 方法有问题,我会执行d::print()
作为b::ef()
的参数,编译我得到这个错误:
“错误:无法将 '' 转换为 'void (*)()'”
你能帮我修一下吗? 谢谢
这是您的代码,已修复。 但我可以看出它有许多“错误”之处,即“按照您的要求进行,但不是您(可能)想要的”。
print
方法需要作用于d
object。但这意味着基数 class 必须知道派生的 class。这很尴尬。 如果基 class 有一个virtual print
function,那么它可以将其传入,并调用该虚拟 function 的派生类覆盖。但这不是我们这里所拥有的。
#include <iostream>
using std::cout;
namespace {
class d;
class b {
public:
b();
void ef(d&, void(d::*)());
};
class d : public b {
public:
d();
void print();
};
b::b() {}
void b::ef(d& dobj, void(d::*f)()) {
(dobj.*f)();
}
d::d() : b() {}
void d::print() {
cout << "WORKS\n";
}
} // anon
int main() {
d obj;
obj.ef(obj, &d::print);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.