'到'函数指针',c++,oop,member-function-pointers"/>

首页 > 解决方案 > 错误:无法转换''到'函数指针'

问题描述

#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 (*)()'”

你能帮我修一下吗?谢谢

标签: c++oopmember-function-pointers

解决方案


这是您的代码,已修复。但是我可以看到它有很多“错误”的地方,从某种意义上说,“做你所要求的,但不是你(可能)想要的。”

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);
}

推荐阅读