指向成员的功能解析

时间:2012-12-13 20:32:06

标签: c++ function-pointers pointer-to-member

这是一个用于过滤对象列表的仿函数。必须使用指向对象类的成员函数的指针进行实​​例化,以此作为访问不同元素的方法。

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

这到底出了什么问题?我不知道如何以另一种方式引用指针。谢谢!

2 个答案:

答案 0 :(得分:1)

要通过指向成员指针的功能进行调用,请使用.*->*。要拨打fun上的File& f1,呼叫为(f1.*fun)()。所以:(f1.*fun)().compare((f2.*fun)())。如果您想使用不需要的显式this->来复合表达式,则必须格外小心:(f1.*(this->fun))().compare((f2.*(this->fun))())

答案 1 :(得分:0)

括号错了:

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