c++ - 错误:无法转换''到'函数指针'
问题描述
#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);
}
我的派生类方法有问题,我将d::print()
作为参数执行b::ef()
,编译时出现此错误:
“错误:无法将 '' 转换为 'void (*)()'”
你能帮我修一下吗?谢谢
解决方案
这是您的代码,已修复。但是我可以看到它有很多“错误”的地方,从某种意义上说,“做你所要求的,但不是你(可能)想要的。”
该print
方法需要作用于一个d
对象。但这意味着基类必须知道派生类。尴尬了。如果基类有一个virtual print
函数,那么它可以传入该函数,并调用派生类覆盖该虚函数。但这不是我们这里所拥有的。
#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);
}
推荐阅读
- mysql - Combine one table with meta data in another table
- python - 用 Pandas 列中的句点替换空格
- docker - 有没有办法在谷歌云构建的 yaml 构建配置文件中的同一步骤中分离不同的参数?
- ios - Transporter 错误 IOS 应用程序图标 1024x1024 丢失
- google-maps - 为 Google Maps JS 实例构建实时标记跟踪器需要学习什么?
- angular - ui-router 在尝试从 angularJS 升级到最新 angular 期间没有看到 ui-view
- terraform - 安装 Terraform 时出错 Err:5 404 Not Found
- batch-file - 批处理脚本在管道中不输出错误
- javascript - 禁用 eslint 的主机配置
- python - Python Readline 循环和子循环