簡體   English   中英

指針到成員函數解析

[英]Pointer-to-member function resolution

這是一個用於過濾對象列表的函子。 必須使用指向對象類的成員函數的指針來實例化它,以作為訪問不同元素的一種方式。

class Filter_Compare : public Filter {
    std::string (File::*fun)();
public:
    Filter_Compare(const char *name, const char *desc, std::string (File::*f)())
        : Filter(name, desc), fun(f)
    {}
    ~Filter_Compare() {};

    int operator () (File* f1, File* f2) { return this->eval(*f1, *f2); }
    int eval(File* f1, File* f2) const { return this->eval(*f1,*f2); }

    int eval(File& f1, File& f2) const {
        return f1.*(this->fun()).compare(f2.*(this->fun()));
    }
};
//an instanciation example :
Filter_Compare fname("Name", "Compare by name", File::getPath);

而g ++返回這些錯誤:

Filter.h:在成員函數'int Filter_Compare :: eval(File&,File&)const'中:Filter.h:48:27:錯誤:必須使用'。 '或'-> '調用'((const Filter_Compare *)this)-> Filter_Compare :: fun(...)'中的指針成員函數,例如'(...-> *((const Filter_Compare *)this)-> Filter_Compare :: fun)(...)'Filter.h:48:53:錯誤:必須使用'。 '或'-> '調用'((const Filter_Compare *)this)-> Filter_Compare :: fun(...)'中的指針成員函數,例如'(...-> *((const Filter_Compare *)this)-> Filter_Compare :: fun)(...)'

我在這里看不到問題,因為我已經在另一個類上使用了它,沒有任何錯誤(嗯,至少它可以編譯,我現在無法運行),其中代碼是:

lit_type eval(File&f)const {return f。*(this-> fun())-thValue; }

這到底是怎么了? 我不知道如何能以另一種方式引用該指針。 謝謝 !

要通過指向成員函數的指針進行調用,請使用.*->* 要在File& f1上調用fun ,調用為(f1.*fun)() 所以: (f1.*fun)().compare((f2.*fun)()) 如果要使用不需要的顯式this-> s來使表達式復雜化,則必須格外小心: (f1.*(this->fun))().compare((f2.*(this->fun))())

括號是錯誤的:

int eval(File& f1, File& f2) const {
    return (f1.*fun)().compare((f2.*fun)());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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