簡體   English   中英

錯誤:無法轉換 '<unresolved overloaded function type> '到'函數指針'</unresolved>

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM