2012-12-13 58 views
2

這是一個用於過濾對象列表的仿函數。它必須實例化一個指向對象類的成員函數的指針,以此來訪問不同的元素。指針到成員函數的解析

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: In member function ‘int Filter_Compare::eval(File&, File&) const’: Filter.h:48:27: error: must use ‘.’ or ‘->’ to call pointer-to-member function in ‘((const Filter_Compare*)this)->Filter_Compare::fun (...)’, e.g. ‘(... ->* ((const Filter_Compare*)this)->Filter_Compare::fun) (...)’ Filter.h:48:53: error: must use ‘.’ or ‘->’ to call pointer-to-member function in ‘((const Filter_Compare*)this)->Filter_Compare::fun (...)’, e.g. ‘(... ->* ((const Filter_Compare*)this)->Filter_Compare::fun) (...)’

我沒有看到這裏的問題,因爲我已經使用這個另一個類沒有任何錯誤(當然,至少它編譯,我現在無法運行),代碼如下:

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

究竟是什麼錯誤?我不知道如何以另一種方式參考指針。謝謝 !

回答

0

括號是錯誤的:

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

你是對的,謝謝。 – 0xeedfade

1

要通過指向成員函數的調用,請使用.*->*。撥打funFile& f1,電話是(f1.*fun)()。所以:(f1.*fun)().compare((f2.*fun)())。如果您想將表達式與不需要的顯式this->複雜化,則必須格外小心:(f1.*(this->fun))().compare((f2.*(this->fun))())

+0

我不認爲你有括號右無論是。我相信它應該是'(f1。* fun)()'(即'()'優先於'。*') –

+0

@DavidRodríguez-dribeas - 你可能是對的。這就是我沒有編譯代碼的原因。固定。 –